<commit_before>//
//  ActionViewController.swift
//  Compass
//
//  Created by <NAME> on 5/31/16.
//  Copyright © 2016 Tennessee Data Commons. All rights reserved.
//

import UIKit
import Just
import ObjectMapper
import Nuke


class ActionViewController: UIViewController{
    //Data
    var upcomingAction: UpcomingAction? = nil;
    var notificationId: Int = -1;
    var mappingId: Int = -1;
    
    //UI components
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var masterContainer: UIView!
    @IBOutlet weak var hero: UIImageView!
    @IBOutlet var actionContainer: UIView!
    @IBOutlet weak var actionTitle: UILabel!
    @IBOutlet weak var behaviorTitle: UILabel!
    @IBOutlet weak var actionDescription: UILabel!
    @IBOutlet weak var laterButton: UIButton!
    @IBOutlet var rewardContainer: UIView!
    @IBOutlet weak var rewardHeader: UILabel!
    @IBOutlet weak var rewardContent: UILabel!
    @IBOutlet var rewardAuthor: UILabel!
    
    var actionConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]();
    var rewardConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]();
    var authorConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]();
    
    
    override func viewDidLoad(){
        //Backup the constraints
        for constraint in masterContainer.constraints{
            if (constraint.firstItem === rewardContainer || constraint.secondItem === rewardContainer){
                rewardConstraints.append(constraint);
            }
            else if (constraint.firstItem === actionContainer || constraint.secondItem === actionContainer){
                actionConstraints.append(constraint);
            }
        }
        for constraint in rewardContainer.constraints{
            if (constraint.firstItem === rewardAuthor || constraint.secondItem === rewardAuthor){
                authorConstraints.append(constraint);
            }
        }
        
        //Remove all items from the master containes (except for the header) and the author
        actionContainer.removeFromSuperview();
        rewardContainer.removeFromSuperview();
        rewardAuthor.removeFromSuperview();
        
        //Either the mappingId is set or the upcomingAction is set (xor), select the propper mappingId
        if (upcomingAction != nil){
            laterButton.hidden = true;
            mappingId = upcomingAction!.getId();
        }
        
        //Fetch the action
        Just.get(API.getActionUrl(mappingId), headers: SharedData.user.getHeaderMap()) { (response) in
            if (response.ok){
                //Parse and populate
                let action = Mapper<UserAction>().map(String(data: response.content!, encoding:NSUTF8StringEncoding)!);
                
                dispatch_async(dispatch_get_main_queue(), {
                    self.actionTitle.text = action!.getTitle();
                    self.behaviorTitle.text = action!.getBehaviorTitle();
                    self.actionDescription.text = action!.getDescription();
                    self.masterContainer.addSubview(self.actionContainer);
                    self.masterContainer.addConstraints(self.actionConstraints);
                    self.masterContainer.setNeedsLayout();
                    self.masterContainer.layoutIfNeeded();
                    self.scrollView.contentSize = self.masterContainer.frame.size;
                });
                
                //Fetch the hero
                let category = SharedData.getCategory(action!.getPrimaryCategoryId());
                if (category != nil && category!.getImageUrl().characters.count != 0){
                    Nuke.taskWith(NSURL(string: category!.getImageUrl())!){
                        self.hero.image = $0.image;
                        }.resume();
                }
                //Fetch the reward
                self.fetchReward();
            }
        };
    }
    
    private func fetchCategory(categoryId: Int){
        Just.get(API.getUserCategoryUrl(categoryId), headers: SharedData.user.getHeaderMap()) { (response) in
            if (response.ok){
                let category = Mapper<ParserModels.UserCategoryArray>().map(String(data: response.content!, encoding:NSUTF8StringEncoding)!)?.categories![0];
                if (category!.getImageUrl().characters.count != 0){
                    Nuke.taskWith(NSURL(string: category!.getImageUrl())!){
                        self.hero.image = $0.image;
                    }.resume();
                }
            }
        }
    }
    
    private func fetchReward(){
        Just.get(API.getRandomRewardUrl()){ (response) in
            if (response.ok){
                print("Reward retrieved");
                let result = String(data: response.content!, encoding:NSUTF8StringEncoding);
                let rewardContent = (Mapper<ParserModels.RewardArray>().map(result)?.rewards![0])!;
                
                dispatch_async(dispatch_get_main_queue(), {
                    self.rewardHeader.text = rewardContent.getHeaderTitle();
                    self.rewardContent.text = rewardContent.getMessage();
                    self.masterContainer.addSubview(self.rewardContainer);<commit_msg>replacing the behaviorTitle label with a button, adding behaviorTitle/behaviorDescription attributes, and displaying both in an Alert<commit_after>//
//  ActionViewController.swift
//  Compass
//
//  Created by <NAME> on 5/31/16.
//  Copyright © 2016 Tennessee Data Commons. All rights reserved.
//

import UIKit
import Just
import ObjectMapper
import Nuke


class ActionViewController: UIViewController{
    //Data
    var upcomingAction: UpcomingAction? = nil;
    var notificationId: Int = -1;
    var mappingId: Int = -1;
    var behaviorDescription: String = ""
    var behaviorTitle: String = ""
    
    //UI components
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var masterContainer: UIView!
    @IBOutlet weak var hero: UIImageView!
    @IBOutlet var actionContainer: UIView!
    @IBOutlet weak var actionTitle: UILabel!
    @IBOutlet weak var behaviorButton: UIButton!
    @IBOutlet weak var actionDescription: UILabel!
    @IBOutlet weak var laterButton: UIButton!
    @IBOutlet var rewardContainer: UIView!
    @IBOutlet weak var rewardHeader: UILabel!
    @IBOutlet weak var rewardContent: UILabel!
    @IBOutlet var rewardAuthor: UILabel!
    
    var actionConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]();
    var rewardConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]();
    var authorConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]();
    

    override func viewDidLoad(){
        //Backup the constraints
        for constraint in masterContainer.constraints{
            if (constraint.firstItem === rewardContainer || constraint.secondItem === rewardContainer){
                rewardConstraints.append(constraint);
            }
            else if (constraint.firstItem === actionContainer || constraint.secondItem === actionContainer){
                actionConstraints.append(constraint);
            }
        }
        for constraint in rewardContainer.constraints{
            if (constraint.firstItem === rewardAuthor || constraint.secondItem === rewardAuthor){
                authorConstraints.append(constraint);
            }
        }
        
        //Remove all items from the master containes (except for the header) and the author
        actionContainer.removeFromSuperview();
        rewardContainer.removeFromSuperview();
        rewardAuthor.removeFromSuperview();
        
        //Either the mappingId is set or the upcomingAction is set (xor), select the propper mappingId
        if (upcomingAction != nil){
            laterButton.hidden = true;
            mappingId = upcomingAction!.getId();
        }
        
        //Fetch the action
        Just.get(API.getActionUrl(mappingId), headers: SharedData.user.getHeaderMap()) { (response) in
            if (response.ok){
                //Parse and populate
                let action = Mapper<UserAction>().map(String(data: response.content!, encoding:NSUTF8StringEncoding)!);
                
                dispatch_async(dispatch_get_main_queue(), {
                    self.actionTitle.text = action!.getTitle();
                    self.behaviorTitle = action!.getBehaviorTitle()
                    self.behaviorButton.setTitle(action!.getBehaviorTitle(), forState: UIControlState.Normal)
                    self.behaviorDescription = action!.getBehaviorDescription();
                    self.actionDescription.text = action!.getDescription();
                    self.masterContainer.addSubview(self.actionContainer);
                    self.masterContainer.addConstraints(self.actionConstraints);
                    self.masterContainer.setNeedsLayout();
                    self.masterContainer.layoutIfNeeded();
                    self.scrollView.contentSize = self.masterContainer.frame.size;
                });
                
                //Fetch the hero
                let category = SharedData.getCategory(action!.getPrimaryCategoryId());
                if (category != nil && category!.getImageUrl().characters.count != 0){
                    Nuke.taskWith(NSURL(string: category!.getImageUrl())!){
                        self.hero.image = $0.image;
                        }.resume();
                }
                //Fetch the reward
                self.fetchReward();
            }
        };
    }
    
    @IBAction func displayBehaviorDetails(sender: AnyObject) {
        let alertController = UIAlertController(title: behaviorTitle, message: behaviorDescription, preferredStyle: .ActionSheet)

        // HACK for changing the style of alerts. NOte the coment about this being private API usage.
        // http://stackoverflow.com/a/26949674/182778
        // Doing the below also looks terrible.
        /*
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = NSTextAlignment.Left
        
        let titleText = NSMutableAttributedString(
            string: behaviorTitle.text!,
            attributes: [
                NSParagraphStyleAttributeName: paragraphStyle,
                //NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleTitle1),
                //NSForegroundColorAttributeName : UIColor.darkGrayColor()
            ]
        )
        
        let messageText = NSMutableAttributedString(
            string: behaviorDescription,
            attributes: [
                NSParagraphStyleAttributeName: paragraphStyle,
                //NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleBody),
                //NSForegroundColorAttributeName : UIColor.darkGrayColor()
            ]
        )
        alertController.setValue(messageText, forKey: "attributedMessage")
        alertController.setValue(titleText, forKey: "attributedTitle")
        */
        
        // Wire up OK action and present the alert.
        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
            // OK doesn't do anything.
        }
        alertController.addAction(OKAction)
        
        self.presentViewController(alertController, animated: true) {
            // Neither does presenting the alert.
        }
    }
    
    private func fetchCategory(categoryId: Int){
        Just.get(API.getUserCategoryUrl(categoryId), headers: SharedData.user.getHeaderMap()) { (response) in
            if (response.ok){
                let category = Mapper<ParserModels.UserCategoryArray>().map(String(data: response.content!, encoding:NSUTF8StringEncoding)!)?.categories![0];
                if (category!.getImageUrl().characters.count != 0){
                    Nuke.taskWith(NSURL(string: category!.getImageUrl())!){
                        self.hero.image = $0.image;
                    }.resume();
                }
            }
        }
    }
    
    private func fetchReward(){
        Just.get(API.getRandomRewardUrl()){ (response) in
            if (response.ok){
                print("Reward retrieved");
                let result = String(data: response.content!, encoding:NSUTF8StringEncoding);
                let rewardContent = (Mapper<ParserModels.RewardArray>().map(result)?.rewards![0])!;
                
                dispatch_async(dispatch_get_main_queue(), {
                    self.rewardHeader.text = rewardContent.getHeaderTitle();
                    self.rewardContent.text = rewardContent.getMessage();
                    self.masterContainer.addSubview(self.rewardContainer);
{'fraction_non_alphanumeric': 0.09625287174205814, 'fraction_numerical': 0.0043571258813277355, 'mean_word_length': 2.1686746987951806, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3514310', 'n_tokens_mistral': 3233, 'n_tokens_neox': 3059, 'n_words': 690}