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

#import "Run.h"

@implementation Run

- (NSTimeInterval)duration
{
    return [[self.laps valueForKeyPath:@"@sum.self"] doubleValue];
}

- (NSTimeInterval)pace
{
    return self.duration / self.laps.count;
}

+ (instancetype)runWithDictionary:(NSDictionary *)dictionary
{
    NSDate *startDate = dictionary[@"startDate"];
    NSArray *laps = dictionary[@"laps"];
    double distance = [dictionary[@"distance"] doubleValue];
    
    if (startDate != nil && laps.count > 0) {
        return [[self alloc] initWithStartDate:startDate
                                          laps:laps
                                      distance:distance];
    }
    
    return nil;
}

- (instancetype)initWithStartDate:(NSDate *)startDate
                             laps:(NSArray *)laps
                         distance:(double)distance
{
    self = [super init];
    
    if (self) {
        self.startDate = startDate;
        self.laps = laps;
        self.distance = distance;
    }
    
    return self;
}

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *representation = [[NSMutableDictionary alloc] init];
    
    if (self.startDate != nil) {
        representation[@"startDate"] = self.startDate;
    }
    
    representation[@"distance"] = @(self.distance);
    representation[@"duration"] = @(self.duration);
    
    // TODO: Create a Lap object that stores its own start and end dates.
    if ([self.laps count] > 0) {
        representation[@"laps"] = self.laps;
    }
    
    return representation;
}

@end
