//
//  TrackSelectionInterfaceController.swift
//  tapalap
//
//  Created by Jeff Kelley on 4/6/15.
//  Copyright (c) 2015 Pragmatic Bookshelf. All rights reserved.
//

import WatchKit
import Foundation


class TrackConfigurationInterfaceController: WKInterfaceController {
    
    @IBOutlet weak var trackNameButton: WKInterfaceButton!
    @IBOutlet weak var lapCountLabel: WKInterfaceLabel!
    @IBOutlet weak var distanceUnitLabel: WKInterfaceLabel!
    
    var lapCount: UInt = 1
    var distanceUnitCount: UInt = 1
    
    var lapDistance: Double {
        let metersPerDistanceUnit: Double = usesMetricSystem() ? 1000 : 1609.34
        
        return (metersPerDistanceUnit * Double(distanceUnitCount)) /
            Double(lapCount)
    }
    
    var trackName: String? {
        didSet(newTrackName) {
            updateTrackNameButton(newTrackName)
        }
    }
    
    func updateTrackNameButton(trackName: String?) {
        let nameToDisplay = trackName ?? "Gym"
        
        self.trackNameButton.setTitle("Track Name: \(nameToDisplay)")
    }
    
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        
        let defaults = NSUserDefaults.standardUserDefaults()
        trackName = defaults.objectForKey("TrackName") as? String
        
        distanceUnitCountSliderAdjusted(1)
    }
    
    func usesMetricSystem() -> Bool {
        let currentLocale = NSLocale.currentLocale()
        return currentLocale.objectForKey(NSLocaleUsesMetricSystem) as! Bool
    }
    
    @IBAction func lapCountSliderAdjusted(value: Float) {
        lapCount = UInt(value)
        
        lapCountLabel.setText("\(lapCount) lap" +
            (lapCount > 1 ? "s are" : " is") + " equal to")
    }
    
    @IBAction func distanceUnitCountSliderAdjusted(value: Float) {
        distanceUnitCount = UInt(value)

        var distanceText: String = "\(distanceUnitCount) "
        
        if usesMetricSystem() {
            distanceText += "km"
        }
        else {
            distanceText += "mile" + (distanceUnitCount > 1 ? "s" : "")
        }
        
        distanceUnitLabel.setText(distanceText)
    }
    
    @IBAction func trackNameButtonPressed() {
        let suggestions = ["Gym", "Indoor Track", "Outdoor Track"]
        
        presentTextInputControllerWithSuggestions(suggestions,
            allowedInputMode: .Plain) {
            if let newName = $0.first as? String {
                self.trackName = newName
            }
        }
    }
    
    @IBAction func doneButtonPressed() {
        let defaults = NSUserDefaults.standardUserDefaults()
        
        defaults.setObject(trackName, forKey: "TrackName")
        defaults.setDouble(lapDistance, forKey: "LapDistance")
        
        dismissController()
    }
    
}
