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

import WatchKit
import Foundation


class TrackSelectionInterfaceController: WKInterfaceController {
    
    @IBOutlet weak var trackNameButton: WKInterfaceButton!
    @IBOutlet weak var lapCountLabel: WKInterfaceLabel!
    @IBOutlet weak var distanceUnitLabel: WKInterfaceLabel!
    
    var lapCount: UInt = 0
    var distanceUnitCount: UInt = 0
    var lapDistance: Double = 0.0 // in meters
    
    var trackName: String? = NSUserDefaults(suiteName: "group.com.slaunchaman.tapalap")?.objectForKey("TrackName") as? String
    
    func usesMetricSystem() -> Bool {
        return NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem) as! Bool
    }
    
    func computeLapDistance() -> Double {
        let metersPerDistanceUnit: Double = usesMetricSystem() ? 1000 : 1609.34
        
        return metersPerDistanceUnit / Double(lapCount)
    }
    
    override func contextForSegueWithIdentifier(segueIdentifier: String) -> AnyObject? {
        return nil
    }
    
    override func contextsForSegueWithIdentifier(segueIdentifier: String) -> [AnyObject]? {
        return nil
    }
    
    @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.trackNameButton.setTitle("Track Name: \(newName)")
            }
        }
    }
    
    @IBAction func doneButtonPressed() {
        let defaults = NSUserDefaults(suiteName: "group.com.slaunchaman.tapalap")
        
        let name: NSString = trackName ?? "Gym"
        
        defaults?.setDouble(computeLapDistance(), forKey: "LapDistance")
        defaults?.setObject(name, forKey: "TrackName")
        
        dismissController()
    }
    
}
