<commit_before>//
//  SubmitWorkoutViewController.swift
//  WorkoutMerge
//
//  Created by <NAME> on 5/29/15.
//  Copyright (c) 2015 <NAME>. All rights reserved.
//
//  This will need a refactor once we submit to more than one service. Intentionally coding to RunKeeper for first iteration.

import UIKit
import CoreData

class SubmitWorkoutViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    
    let kSwitchPrefTotalCalories = "kSwitchPrefTotalCalories"
    let kSwitchPrefTotalDistance = "kSwitchPrefTotalDistance"
    let kSwitchPrefAverageHeartRate = "kSwitchPrefAverageHeartRate"
    
    let defaults = NSUserDefaults.standardUserDefaults()
    
    var workoutSyncAPI: WorkoutSyncAPI = WorkoutSyncAPI()
    var resultWorkoutData: (UUID: NSUUID?, type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?, otherType: String?, activityName: String?)
    var workoutData: (UUID: NSUUID?, type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?, otherType: String?, activityName: String?) {
        didSet {
            self.resultWorkoutData = self.workoutData
            
            // Check defaults for switches
            if let switchPrefTotalCalories = defaults.valueForKey(kSwitchPrefTotalCalories) as? Bool where !switchPrefTotalCalories {
                self.resultWorkoutData.totalCalories = nil
            }
            if let switchPrefTotalDistance = defaults.valueForKey(kSwitchPrefTotalDistance) as? Bool where !switchPrefTotalDistance {
                self.resultWorkoutData.totalDistance = nil
            }
            if let switchPrefAverageHeartRate = defaults.valueForKey(kSwitchPrefAverageHeartRate) as? Bool where !switchPrefAverageHeartRate {
                self.resultWorkoutData.averageHeartRate = nil
            }
        }
    }
    var picker:Int = 0
    var pickerSelection:Int = 0
    
    var useMetric = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.useMetric = self.defaults.stringForKey("distanceUnit") == "meters"
        
        if let uuid = self.resultWorkoutData.UUID?.UUIDString, syncLog = self.syncLog(uuid) {
            if let note = syncLog.valueForKey("note") as? String {
                self.resultWorkoutData.notes = note
            }
            if let activityName = syncLog.valueForKey("name") as? String {
                self.resultWorkoutData.activityName = activityName
            }
            
            // FIXME find a better way
            if let workoutSyncAPI = self.workoutSyncAPI as? StravaAPI {
                // Strava Workout Types
                if let workoutType = syncLog.valueForKey("workoutTypeStrava") as? String {
                    self.resultWorkoutData.type = workoutType
                }
            } else {
                // Default is RunKeeper
                if let workoutType = syncLog.valueForKey("workoutType") as? String {
                    self.resultWorkoutData.type = workoutType
                }
                if let workoutOtherType = syncLog.valueForKey("workoutOtherType") as? String {
                    self.resultWorkoutData.otherType = workoutOtherType
                }
            }
        }
        
        self.tableView.contentInset = UIEdgeInsetsMake(20, self.tableView.contentInset.left, self.tableView.contentInset.bottom, self.tableView.contentInset.right)
    }
    
    override func viewDidAppear(animated: Bool) {
        println("workoutData: \(workoutData)")
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var rows = 7
        
        if let workoutSyncAPI = self.workoutSyncAPI as? StravaAPI {
            // Add 1 for workout Name
            rows++
        }
        
        if resultWorkoutData.type == "Other" {
            // Select other type
            return rows++
        }
        return rows
    }
    
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
        case 0:
            return "Sync Data"
        default:
            return ""
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell
        
        func staticCell() -> UITableViewCell {
            return tableView.dequeueReusableCellWithIdentifier("submitStaticCell", forIndexPath: indexPath) as! UITableViewCell
        }
        
        func dynamicCell() -> UITableViewCell {
            return tableView.dequeueReusableCellWithIdentifier("submitDynamicCell", forIndexPath: indexPath) as! UITableViewCell
        }
        
        func staticInputCell() -> UITableViewCell {
            return tableView.dequeueReusableCellWithIdentifier("submitStaticInputCell", forIndexPath: indexPath) as! UITableViewCell
        }
        
        func setTitle(title: String?, cell: SubmitWorkoutTableViewCell?) {
            if let l = cell?.titleLabel, t = title {
                l.text = t
            }
        }
        
        func setSubtitle(title: String?, cell: SubmitWorkoutTableViewCell?) {
            if let l = cell?.subtitleLabel, t = title {
                l.text = t
            }
        }
//        (type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?)
        
        var row = indexPath.row
        
        // ugly hack for now to add a conditional cell
        if resultWorkoutData.type == "Other" {
            
            
            if row > 1 {
                // reset so our case works
                row--
            } else if row == 1 {
                cell = staticInputCell()
                cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
                cell.selectionStyle = UITableViewCellSelectionStyle.Default
                setTitle("Other", cell as? SubmitWorkoutTableViewCell)
                setSubtitle(self.resultWorkoutData.otherType == nil ? "" : self.resultWorkoutData.otherType, cell as? SubmitWorkoutTableViewCell)
                return cell
            }
        }
        
        switch row {
        case 0:
            cell = staticInputCell()
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            cell.selectionStyle = UITableViewCellSelectionStyle.Default
            setTitle("Workout Type", cell as? SubmitWorkoutTableViewCell)
            setSubtitle(self.resultWorkoutData.type, cell as? SubmitWorkoutTableViewCell)
        case 1:
            cell = staticCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Duration", cell as? SubmitWorkoutTableViewCell)
            setSubtitle(stringFromTimeInterval(self.resultWorkoutData.duration), cell as? SubmitWorkoutTableViewCell)
        case 2:
            cell = dynamicCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Calories Burned", cell as? SubmitWorkoutTableViewCell)
            if let totalCalories = self.workoutData.totalCalories {
                setSubtitle(totalCalories.intString(), cell as? SubmitWorkoutTableViewCell)
            }
            if let cell = cell as? SubmitWorkoutTableViewCell {
                cell.switchChangedCallback = { isOn in
                    self.resultWorkoutData.totalCalories = isOn ? self.workoutData.totalCalories : nil
                    self.defaults.setBool(isOn, forKey: self.kSwitchPrefTotalCalories)
                }
                if let switchState = defaults.valueForKey(self.kSwitchPrefTotalCalories) as? Bool {
                    cell.setSwitchState(switchState)
                }
            }
        case 3:
            cell = dynamicCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Distance", cell as? SubmitWorkoutTableViewCell)
            if let totalDistance = self.workoutData.totalDistance {
                if self.useMetric {
                    setSubtitle(totalDistance.intString()! + " meters", cell as? SubmitWorkoutTableViewCell)
                } else {
                    let miles = totalDistance * 0.00062137
                    setSubtitle(miles.shortDecimalString()! + " miles", cell as? SubmitWorkoutTableViewCell)
                }
            }
            if let cell = cell as? SubmitWorkoutTableViewCell {
                cell.switchChangedCallback = { isOn in
                    self.resultWorkoutData.totalDistance = isOn ? self.workoutData.totalDistance : nil
                    self.defaults.setBool(isOn, forKey: self.kSwitchPrefTotalDistance)
                }
                if let switchState = defaults.valueForKey(self.kSwitchPrefTotalDistance) as? Bool {
                    cell.setSwitchState(switchState)
                }
            }
        case 4:
            cell = dynamicCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Avg Heart Rate", cell as? SubmitWorkoutTableViewCell)
            if let averageHeartRate = self.workoutData.averageHeartRate {
                setSubtitle(averageHeartRate.intString()! + " BPM", cell as? SubmitWorkoutTableViewCell)
            }
            if let cell = cell as? SubmitWorkoutTableViewCell {
                cell.switchChangedCallback = { isOn in
                    self.resultWorkoutData.averageHeartRate = isOn ? self.workoutData.averageHeartRate : nil
                    self.defaults.setBool(isOn, forKey: self.kSwitchPrefAverageHeartRate)
                }
                if let switchState = defaults.valueForKey(self.kSwitchPrefAverageHeartRate) as? Bool {
                    cell.setSwitchState(switchState)
                }
            }
        case 5:
            cell = staticCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Date", cell as? SubmitWorkoutTableViewCell)
            if let startTime = self.workoutData.startTime {
                setSubtitle(startTime.shortDateString(), cell as? SubmitWorkoutTableViewCell)
            }
        case 6:
            cell = staticCell()
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            cell.selectionStyle = UITableViewCellSelectionStyle.Default
            setTitle("Notes", cell as? SubmitWorkoutTableViewCell)
            if let notes = self.resultWorkoutData.notes {
                setSubtitle(notes, cell as? SubmitWorkoutTableViewCell)
            } else {
                setSubtitle("", cell as? SubmitWorkoutTableViewCell)
            }
        case 7:
            cell = staticCell()
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            cell.selectionStyle = UITableViewCellSelectionStyle.Default
            setTitle("Name", cell as? SubmitWorkoutTableViewCell)<commit_msg>strava shows unavailable cells as disabled<commit_after>//
//  SubmitWorkoutViewController.swift
//  WorkoutMerge
//
//  Created by <NAME> on 5/29/15.
//  Copyright (c) 2015 <NAME>. All rights reserved.
//
//  This will need a refactor once we submit to more than one service. Intentionally coding to RunKeeper for first iteration.

import UIKit
import CoreData

class SubmitWorkoutViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    
    let kSwitchPrefTotalCalories = "kSwitchPrefTotalCalories"
    let kSwitchPrefTotalDistance = "kSwitchPrefTotalDistance"
    let kSwitchPrefAverageHeartRate = "kSwitchPrefAverageHeartRate"
    
    let defaults = NSUserDefaults.standardUserDefaults()
    
    var workoutSyncAPI: WorkoutSyncAPI = WorkoutSyncAPI()
    var resultWorkoutData: (UUID: NSUUID?, type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?, otherType: String?, activityName: String?)
    var workoutData: (UUID: NSUUID?, type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?, otherType: String?, activityName: String?) {
        didSet {
            self.resultWorkoutData = self.workoutData
            
            // Check defaults for switches
            if let switchPrefTotalCalories = defaults.valueForKey(kSwitchPrefTotalCalories) as? Bool where !switchPrefTotalCalories {
                self.resultWorkoutData.totalCalories = nil
            }
            if let switchPrefTotalDistance = defaults.valueForKey(kSwitchPrefTotalDistance) as? Bool where !switchPrefTotalDistance {
                self.resultWorkoutData.totalDistance = nil
            }
            if let switchPrefAverageHeartRate = defaults.valueForKey(kSwitchPrefAverageHeartRate) as? Bool where !switchPrefAverageHeartRate {
                self.resultWorkoutData.averageHeartRate = nil
            }
        }
    }
    var picker:Int = 0
    var pickerSelection:Int = 0
    
    var useMetric = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.useMetric = self.defaults.stringForKey("distanceUnit") == "meters"
        
        if let uuid = self.resultWorkoutData.UUID?.UUIDString, syncLog = self.syncLog(uuid) {
            if let note = syncLog.valueForKey("note") as? String {
                self.resultWorkoutData.notes = note
            }
            if let activityName = syncLog.valueForKey("name") as? String {
                self.resultWorkoutData.activityName = activityName
            }
            
            // FIXME find a better way
            if let workoutSyncAPI = self.workoutSyncAPI as? StravaAPI {
                // Strava Workout Types
                if let workoutType = syncLog.valueForKey("workoutTypeStrava") as? String {
                    self.resultWorkoutData.type = workoutType
                }
            } else {
                // Default is RunKeeper
                if let workoutType = syncLog.valueForKey("workoutType") as? String {
                    self.resultWorkoutData.type = workoutType
                }
                if let workoutOtherType = syncLog.valueForKey("workoutOtherType") as? String {
                    self.resultWorkoutData.otherType = workoutOtherType
                }
            }
        }
        
        self.tableView.contentInset = UIEdgeInsetsMake(20, self.tableView.contentInset.left, self.tableView.contentInset.bottom, self.tableView.contentInset.right)
    }
    
    override func viewDidAppear(animated: Bool) {
        println("workoutData: \(workoutData)")
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var rows = 7
        
        if let workoutSyncAPI = self.workoutSyncAPI as? StravaAPI {
            // Add 1 for workout Name
            rows++
        }
        
        if resultWorkoutData.type == "Other" {
            // Select other type
            return rows++
        }
        return rows
    }
    
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
        case 0:
            return "Sync Data"
        default:
            return ""
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell
        
        func staticCell() -> UITableViewCell {
            return tableView.dequeueReusableCellWithIdentifier("submitStaticCell", forIndexPath: indexPath) as! UITableViewCell
        }
        
        func dynamicCell() -> UITableViewCell {
            return tableView.dequeueReusableCellWithIdentifier("submitDynamicCell", forIndexPath: indexPath) as! UITableViewCell
        }
        
        func staticInputCell() -> UITableViewCell {
            return tableView.dequeueReusableCellWithIdentifier("submitStaticInputCell", forIndexPath: indexPath) as! UITableViewCell
        }
        
        func disabledCell() -> UITableViewCell {
            if let cell = tableView.dequeueReusableCellWithIdentifier("submitStaticInputCell", forIndexPath: indexPath) as? SubmitWorkoutTableViewCell {
                cell.setDisabled(true)
                return cell
            } else {
                return tableView.dequeueReusableCellWithIdentifier("submitStaticCell", forIndexPath: indexPath) as! UITableViewCell
            }
        }
        
        func setTitle(title: String?, cell: SubmitWorkoutTableViewCell?) {
            if let l = cell?.titleLabel, t = title {
                l.text = t
            }
        }
        
        func setSubtitle(title: String?, cell: SubmitWorkoutTableViewCell?) {
            if let l = cell?.subtitleLabel, t = title {
                l.text = t
            }
        }
//        (type: String?, startTime: NSDate?, totalDistance: Double?, duration: Double?, averageHeartRate: Int?, totalCalories: Double?, notes: String?)
        
        var row = indexPath.row
        
        // ugly hack for now to add a conditional cell
        if resultWorkoutData.type == "Other" {
            
            
            if row > 1 {
                // reset so our case works
                row--
            } else if row == 1 {
                cell = staticInputCell()
                cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
                cell.selectionStyle = UITableViewCellSelectionStyle.Default
                setTitle("Other", cell as? SubmitWorkoutTableViewCell)
                setSubtitle(self.resultWorkoutData.otherType == nil ? "" : self.resultWorkoutData.otherType, cell as? SubmitWorkoutTableViewCell)
                return cell
            }
        }
        
        switch row {
        case 0:
            cell = staticInputCell()
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            cell.selectionStyle = UITableViewCellSelectionStyle.Default
            setTitle("Workout Type", cell as? SubmitWorkoutTableViewCell)
            setSubtitle(self.resultWorkoutData.type, cell as? SubmitWorkoutTableViewCell)
        case 1:
            cell = staticCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Duration", cell as? SubmitWorkoutTableViewCell)
            setSubtitle(stringFromTimeInterval(self.resultWorkoutData.duration), cell as? SubmitWorkoutTableViewCell)
        case 2:
            if let strava = self.workoutSyncAPI as? StravaAPI {
                cell = disabledCell()
            } else {
                cell = dynamicCell()
            }
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Calories Burned", cell as? SubmitWorkoutTableViewCell)
            if let totalCalories = self.workoutData.totalCalories {
                setSubtitle(totalCalories.intString(), cell as? SubmitWorkoutTableViewCell)
            }
            if let cell = cell as? SubmitWorkoutTableViewCell {
                cell.switchChangedCallback = { isOn in
                    self.resultWorkoutData.totalCalories = isOn ? self.workoutData.totalCalories : nil
                    self.defaults.setBool(isOn, forKey: self.kSwitchPrefTotalCalories)
                }
                if !cell.isDisabled {
                    if let switchState = defaults.valueForKey(self.kSwitchPrefTotalCalories) as? Bool {
                        cell.setSwitchState(switchState)
                    }
                }
            }
        case 3:
            cell = dynamicCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Distance", cell as? SubmitWorkoutTableViewCell)
            if let totalDistance = self.workoutData.totalDistance {
                if self.useMetric {
                    setSubtitle(totalDistance.intString()! + " meters", cell as? SubmitWorkoutTableViewCell)
                } else {
                    let miles = totalDistance * 0.00062137
                    setSubtitle(miles.shortDecimalString()! + " miles", cell as? SubmitWorkoutTableViewCell)
                }
            }
            if let cell = cell as? SubmitWorkoutTableViewCell {
                cell.switchChangedCallback = { isOn in
                    self.resultWorkoutData.totalDistance = isOn ? self.workoutData.totalDistance : nil
                    self.defaults.setBool(isOn, forKey: self.kSwitchPrefTotalDistance)
                }
                if let switchState = defaults.valueForKey(self.kSwitchPrefTotalDistance) as? Bool {
                    cell.setSwitchState(switchState)
                }
            }
        case 4:
            if let strava = self.workoutSyncAPI as? StravaAPI {
                cell = disabledCell()
            } else {
                cell = dynamicCell()
            }
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Avg Heart Rate", cell as? SubmitWorkoutTableViewCell)
            if let averageHeartRate = self.workoutData.averageHeartRate {
                setSubtitle(averageHeartRate.intString()! + " BPM", cell as? SubmitWorkoutTableViewCell)
            }
            if let cell = cell as? SubmitWorkoutTableViewCell {
                cell.switchChangedCallback = { isOn in
                    self.resultWorkoutData.averageHeartRate = isOn ? self.workoutData.averageHeartRate : nil
                    self.defaults.setBool(isOn, forKey: self.kSwitchPrefAverageHeartRate)
                }
                if !cell.isDisabled {
                    if let switchState = defaults.valueForKey(self.kSwitchPrefAverageHeartRate) as? Bool {
                        cell.setSwitchState(switchState)
                    }
                }
            }
        case 5:
            cell = staticCell()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            setTitle("Date", cell as? SubmitWorkoutTableViewCell)
            if let startTime = self.workoutData.startTime {
                setSubtitle(startTime.shortDateString(), cell as? SubmitWorkoutTableViewCell)
            }
        case 6:
            cell = staticCell()
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            cell.selectionStyle = UITableViewCellSelectionStyle.Default
            setTitle("Notes", cell as? SubmitWorkoutTableViewCell)
            if let notes = self.resultWorkoutData.notes {
                setSubtitle(notes, cell as? SubmitWorkoutTableViewCell)
            } else {
                setSubtitle("", cell as? SubmitWorkoutTableViewCell)
            }
        case 7:
            cell = staticCell()
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            cell.selectionStyle = UITableViewCellSelectionStyle.Default
            setTitle("Name", cell as? SubmitWorkoutTableViewCell)
{'fraction_non_alphanumeric': 0.07407096720073819, 'fraction_numerical': 0.0030198808824763025, 'mean_word_length': 2.069387229660144, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 24, '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': '4111730', 'n_tokens_mistral': 6357, 'n_tokens_neox': 5974, 'n_words': 1355}