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

import Foundation

class Run {
    
    let distance: Double // in meters
    let laps: [NSTimeInterval]
    let startDate: NSDate
    
    var duration: NSTimeInterval {
        return laps.reduce(0, combine: +)
    }
    
    var pace: NSTimeInterval {
        return duration / NSTimeInterval(laps.count)
    }
    
    convenience init?(dictionary: [NSObject: AnyObject]) {
        if let distance = dictionary["distance"] as? Double,
            laps = dictionary["laps"] as? [NSTimeInterval],
            startDate = dictionary["startDate"] as? NSDate {
                self.init(distance: distance,
                    laps: laps,
                    startDate: startDate)
        }
        else {
            // Having to provide default values is a bug in Apple’s Swift compiler
            // as of Swift 1.2:
            // https://devforums.apple.com/thread/251388?start=0&tstart=0#1062922
            self.init(distance: 0, laps: [0], startDate: NSDate())
            return nil
        }
    }

    init(distance: Double, laps: [NSTimeInterval], startDate: NSDate) {
        self.distance = distance
        self.laps = laps
        self.startDate = startDate
    }
    
    func dictionaryRepresentation() -> [NSObject: AnyObject] {
        return [
            "distance": distance,
            "duration": duration,
            "laps": laps,
            "startDate": startDate,
        ]
    }

}
