/***
 * Excerpted from "Developing for Apple Watch",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/jkwatch for more book information.
***/
//
//  GoRunningInterfaceController.m
//  tapalap WatchKit Extension
//
//  Created by Jeff Kelley on 2/27/15.
//  Copyright (c) 2015 Pragmatic Bookshelf. All rights reserved.
//


#import "GoRunningInterfaceController.h"

#import "Run.h"
#import "Track.h"


@interface GoRunningInterfaceController ()

@property (readonly, nonatomic) Track *track;
@property (strong, nonatomic) NSArray *runs;

@property (weak, nonatomic) IBOutlet WKInterfaceLabel *trackTitleLabel;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *trackDistanceLabel;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *runCountLabel;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *runsSubtitleLabel;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *averagePaceLabel;

@property (nonatomic, readonly) NSLengthFormatter *lengthformatter;
@property (nonatomic, readonly) NSDateComponentsFormatter *paceFormatter;

@end


@implementation GoRunningInterfaceController

- (Track *)track
{
    Track *track = nil;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *trackName = [defaults objectForKey:@"TrackName"];
    
    if (trackName != nil) {
        track =
        [[Track alloc] initWithName:trackName
                        lapDistance:[defaults doubleForKey:@"LapDistance"]];
    }
    else {
        track = [[Track alloc] initWithName:@"Gym"
                                lapDistance:402.336];
    }
    
    return track;
}

- (NSArray *)runs
{
    if (_runs == nil) {
        NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:
                                    @"group.com.pragprog.tapalap"];
        
        NSArray *runDicts = [defaults objectForKey:@"Runs"];
        
        NSMutableArray *runs = [[NSMutableArray alloc] init];

        for (NSDictionary *runDict in runDicts) {
            Run *run = [Run runWithDictionary:runDict];
            
            if (run != nil) {
                [runs addObject:run];
            }
        }
        
        _runs = [NSArray arrayWithArray:runs];
    }
    
    return _runs;
}

- (void)awakeWithContext:(id)context
{
    [super awakeWithContext:context];
    
    [self.trackDistanceLabel setText:
     [self.lengthformatter stringFromMeters:
      self.track.lapDistance]];
    
    [self.trackTitleLabel setText:self.track.name];
}

- (void)willActivate
{
    [super willActivate];
    
    [self.trackDistanceLabel setText:
     [self.lengthformatter stringFromMeters:self.track.lapDistance]];
    
    [self.trackTitleLabel setText:self.track.name];
    
    [self.runCountLabel setText:
     [NSString stringWithFormat:@"%lu", (unsigned long)self.runs.count]];
    
    if (self.runs.count > 0) {
        [self.runsSubtitleLabel setText:self.runs.count > 0 ? @"Runs" : @"Run"];
        
        double totalDistance =
        [[self.runs valueForKeyPath:@"@sum.distance"] doubleValue];
        
        NSTimeInterval totalDuration =
        [[self.runs valueForKeyPath:@"@sum.duration"] doubleValue];
        
        NSTimeInterval averagePace = 0.0;
        
        if ([[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue]) {
            double kilometers = totalDistance / 1000;
            averagePace =  totalDuration / kilometers;
        }
        else {
            double miles = totalDistance / 1609.34;
            averagePace = totalDuration / miles;
        }
        
        [self.averagePaceLabel setText:
         [self.paceFormatter stringFromTimeInterval:averagePace]];
    }
    else {
        [self.runsSubtitleLabel setText:@"Runs"];
        [self.averagePaceLabel setText:@"0:00"];
    }
}

- (void)didDeactivate
{
    [super didDeactivate];
    
    self.runs = nil;
}

@synthesize lengthformatter = _lengthformatter;

- (NSLengthFormatter *)lengthformatter
{
    if (_lengthformatter == nil) {
        _lengthformatter = [[NSLengthFormatter alloc] init];
        
        _lengthformatter.numberFormatter.lenient = YES;
        _lengthformatter.numberFormatter.maximumFractionDigits = 2;
        _lengthformatter.numberFormatter.usesSignificantDigits = YES;
        _lengthformatter.numberFormatter.maximumSignificantDigits = 3;
        _lengthformatter.unitStyle = NSFormattingUnitStyleShort;
    }
    
    return _lengthformatter;
}

@synthesize paceFormatter = _paceFormatter;

- (NSDateComponentsFormatter *)paceFormatter
{
    if (_paceFormatter == nil) {
        _paceFormatter = [[NSDateComponentsFormatter alloc] init];
        
        _paceFormatter.unitsStyle =
        NSDateComponentsFormatterUnitsStylePositional;
    }
    
    return _paceFormatter;
}

- (IBAction)startRunButtonPressed
{
    NSString *controllerName = @"RunTimerInterfaceController";
    
    [WKInterfaceController reloadRootControllersWithNames:@[controllerName]
                                                 contexts:nil];
}

- (IBAction)trackButtonPressed
{
    [self presentControllerWithName:@"TrackConfiguration"
                            context:nil];
}

@end
