/***
 * 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.
***/
//
//  RunTimerInterfaceController.m
//  tapalap
//
//  Created by Jeff Kelley on 2/27/15.
//  Copyright (c) 2015 Pragmatic Bookshelf. All rights reserved.
//

#import "RunTimerInterfaceController.h"
@import HealthKit;
#import "Run.h"
#import "Track.h"


@interface RunTimerInterfaceController ()
@property (weak, nonatomic) IBOutlet WKInterfaceButton *endRunButton;
@property (weak, nonatomic) IBOutlet WKInterfaceButton *finishLapButton;
@property (weak, nonatomic) IBOutlet WKInterfaceLabel *distanceLabel;
@property (strong, nonatomic) Track *track;
@property (assign, nonatomic) double distance;

@end


@implementation RunTimerInterfaceController

- (instancetype)init
{
    self = [super init];
    
    if (self) {
        self.track = [[Track alloc] initWithName:@"Track"
                                     lapDistance:500.0];
    }
    
    return self;
}

- (void)willActivate
{
    [super willActivate];
    
    [self updateDistanceLabel];
}

- (IBAction)finishLapButtonPressed
{
    self.distance += self.track.lapDistance;
    [self updateDistanceLabel];
}

- (void)updateDistanceLabel
{
    NSLengthFormatter *lengthFormatter =
    [[NSLengthFormatter alloc] init];
    
    lengthFormatter.numberFormatter.maximumSignificantDigits = 3;
    
    [self.distanceLabel setText:
     [lengthFormatter stringFromMeters:self.distance]];
}

- (IBAction)endRunButtonPressed
{
    [self endRun];
}

/*
- (void)endRun
{
    // The rest of this method is to be written.

    NSArray *names = @[@"Go Running", @"Run Log"];
    
    [WKInterfaceController reloadRootControllersWithNames:names
                                                 contexts:nil];
}
*/

- (void)endRun
{
    Run *run = [[Run alloc] initWithStartDate:[NSDate date]
                                         laps:@[@60.0, @60.0, @60.0, @60.0, @60.0]
                                     distance:2500];
    
    [self saveRunToUserDefaults:run];
    [self saveRunToHealthKit:run];
    
    NSArray *names = @[@"Go Running", @"Run Log"];
    NSArray *contexts = @[[NSNull null], run];
    
    [WKInterfaceController reloadRootControllersWithNames:names
                                                 contexts:contexts];
}

- (void)saveRunToHealthKit:(Run *)run
{
    NSDictionary *userInfo = @{ @"RunToSave": [run dictionaryRepresentation] };
    
    [WKInterfaceController openParentApplication:userInfo
                                           reply:^(NSDictionary *replyInfo,
                                                   NSError *error) {
                                               if (replyInfo != nil) {
                                                   [self handleReply:replyInfo];
                                               }
                                               else if (error != nil){
                                                   NSLog(@"Error in reply: %@",
                                                         [error description]);
                                               }
                                           }];
}

- (void)handleReply:(NSDictionary *)replyInfo
{
    BOOL success = [replyInfo[@"Success"] boolValue];
    
    if (!success) {
        NSLog(@"Couldn’t save run!");
        
        NSString *error = replyInfo[@"Error"];
        
        if (error != nil) {
            NSLog(@"Error: %@", error);
        }
    }
}

- (void)saveRunToUserDefaults:(Run *)run
{
    NSUserDefaults *sharedDefaults =
    [[NSUserDefaults alloc] initWithSuiteName:@"group.com.pragprog.tapalap"];
    
    NSArray *savedRuns = [sharedDefaults objectForKey:@"Runs"];
    
    if (savedRuns == nil) {
        savedRuns = @[];
    }

    savedRuns = [savedRuns arrayByAddingObject:[run dictionaryRepresentation]];
    
    [sharedDefaults setObject:savedRuns forKey:@"Runs"];
}

@end
