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


#import "ViewController.h"

#import "AppDelegate.h"

@interface ViewController () <UITableViewDataSource>

@property (nonatomic, readonly) NSArray *runs;
@property (strong, readonly, nonatomic) NSLengthFormatter *distanceFormatter;
@property (strong, readonly, nonatomic) NSDateFormatter *runDateFormatter;

@end


@implementation ViewController

@synthesize distanceFormatter = _distanceFormatter;
@synthesize runDateFormatter = _runDateFormatter;

#pragma mark - View Controller Lifecycle

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    HKHealthStore *healthStore = APP_DELEGATE.healthStore;
    
    HKObjectType *workoutType = [HKObjectType workoutType];
    
    HKAuthorizationStatus workoutAuthorizationStatus =
    [healthStore authorizationStatusForType:workoutType];
    
    HKObjectType *distanceType =
    [HKQuantityType quantityTypeForIdentifier:
     HKQuantityTypeIdentifierDistanceWalkingRunning];
    
    HKAuthorizationStatus distanceAuthorizationStatus =
    [healthStore authorizationStatusForType:distanceType];
    
    if (workoutAuthorizationStatus != HKAuthorizationStatusSharingAuthorized ||
        distanceAuthorizationStatus != HKAuthorizationStatusSharingAuthorized) {
        NSSet *typesToShare = [NSSet setWithObjects:workoutType, distanceType, nil];
        
        [healthStore requestAuthorizationToShareTypes:typesToShare
                                            readTypes:nil
                                           completion:^(BOOL success,
                                                        NSError *error) {
                                               if (!success) {
                                                   NSLog(@"Failed to authorize: %@",
                                                         [error description]);
                                               }
                                           }];
    }
    else if (workoutAuthorizationStatus == HKAuthorizationStatusSharingDenied) {
        [self displayAlertForHealthKitAccessDenied];
    }
}

#pragma mark - UITableViewDataSource Protocol Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return self.runs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"RunCell";
    
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                      reuseIdentifier:cellIdentifier];
    }
    
    NSDictionary *runDictionary = self.runs[indexPath.row];
    
    cell.textLabel.text = [self.distanceFormatter stringFromMeters:
                           [runDictionary[@"distance"] doubleValue]];
    
    cell.detailTextLabel.text = [self.runDateFormatter stringFromDate:
                                 runDictionary[@"startDate"]];
    
    return cell;
}

#pragma mark -

- (void)displayAlertForHealthKitAccessDenied
{
    NSString *message = @"You’ve disabled HealthKit access for tapalap. Please "
    "open your Health application and restore access.";
    
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:@"Sharing Denied"
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK"
                                                            style:UIAlertActionStyleDefault
                                                          handler:NULL];
    
    [alert addAction:defaultAction];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

- (NSArray *)runs
{
    NSUserDefaults *sharedDefaults =
    [[NSUserDefaults alloc] initWithSuiteName:@"group.com.pragprog.tapalap"];
    
    return [sharedDefaults objectForKey:@"Runs"];
}

- (NSLengthFormatter *)distanceFormatter
{
    if (_distanceFormatter == nil) {
        _distanceFormatter = [[NSLengthFormatter alloc] init];
        _distanceFormatter.numberFormatter.maximumSignificantDigits = 3;
    }
    
    return _distanceFormatter;
}

- (NSDateFormatter *)runDateFormatter
{
    if (_runDateFormatter == nil) {
        _runDateFormatter = [[NSDateFormatter alloc] init];
        _runDateFormatter.dateStyle = NSDateFormatterMediumStyle;
        _runDateFormatter.timeStyle = NSDateFormatterNoStyle;
    }
    
    return _runDateFormatter;
}

#pragma mark -

@end
