//
//  GoRunningInterfaceController.swift
//  TapALap
//
//  Created by Jeff Kelley on 4/27/15.
//  Copyright (c) 2015 Pragmatic Bookshelf. All rights reserved.
//

import WatchKit

class GoRunningInterfaceController: WKInterfaceController {
    
    var track: Track {
        let defaults = NSUserDefaults.standardUserDefaults()
        
        if let trackName = defaults.objectForKey("TrackName") as? String,
            lapDistance = defaults.objectForKey("LapDistance") as? Double {
            return Track(name: trackName, lapDistance: lapDistance)
        }
        else {
            return Track(name: "Gym", lapDistance: 402.336)
        }
    }

    @IBOutlet weak var titleLabel: WKInterfaceLabel!
    @IBOutlet weak var distanceLabel: WKInterfaceLabel!
    
    @IBOutlet weak var runCountLabel: WKInterfaceLabel!
    @IBOutlet weak var runsSubtitleLabel: WKInterfaceLabel!
    @IBOutlet weak var averagePaceLabel: WKInterfaceLabel!
    
    lazy var runs: [Run]? = {
        var runs: [Run]?
        
        let defaults = NSUserDefaults(suiteName: "group.com.pragprog.tapalap")
        
        if let dicts = defaults?.objectForKey("Runs") as? [[NSObject: AnyObject]] {
            runs = []
            
            for dict in dicts {
                if let run = Run(dictionary: dict) {
                    runs?.append(run)
                }
            }
        }
        
        return runs
    }()
    
    lazy var lengthFormatter: NSLengthFormatter = {
        let formatter = NSLengthFormatter()
        
        formatter.numberFormatter.lenient = true
        formatter.numberFormatter.maximumFractionDigits = 2
        formatter.numberFormatter.usesSignificantDigits = true
        formatter.numberFormatter.maximumSignificantDigits = 3
        
        formatter.unitStyle = .Short
        
        return formatter
    }()
    
    lazy var paceFormatter: NSDateComponentsFormatter = {
        let formatter = NSDateComponentsFormatter()
        formatter.unitsStyle = .Positional
        return formatter
    }()
    
    override func willActivate() {
        super.willActivate()
        
        distanceLabel.setText(lengthFormatter.stringFromMeters(track.lapDistance))
        titleLabel.setText(track.name)
        
        if let runs = runs {
            runCountLabel.setText("\(runs.count)")
            runsSubtitleLabel.setText(runs.count == 1 ? "Run" : "Runs")
            
            let totalDistance = runs.map { $0.distance }.reduce(0,combine: +)
            let totalDuration = runs.map { $0.duration }.reduce(0,combine: +)
            
            let averagePace: NSTimeInterval
            
            if NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem) as! Bool {
                let kilometers = totalDistance / 1000
                averagePace =  totalDuration / kilometers
            }
            else {
                let miles = totalDistance / 1609.34
                averagePace = totalDuration / miles
            }
            
            averagePaceLabel.setText(paceFormatter.stringFromTimeInterval(averagePace))
        }
        else {
            runCountLabel.setText("0")
            runsSubtitleLabel.setText("Runs")
            averagePaceLabel.setText("0:00")
        }
    }
    
    override func didDeactivate() {
        super.didDeactivate()
        
        runs = nil
    }
    
    @IBAction func startRunButtonPressed() {
        let names = ["RunTimer"]
        WKInterfaceController.reloadRootControllersWithNames(names, contexts: nil)
    }
    
    @IBAction func trackButtonPressed() {
        presentControllerWithName("TrackConfiguration", context: nil)
    }
    
}
