//
//  TodayViewController.m
//  LifeLog
//
//  Created by Nguyen Van Phong on 7/29/17.
//  Copyright © 2017 PhongNV. All rights reserved.
//

#import "TodayViewController.h"
#import <CircleProgressBar/CircleProgressBar.h>
#import <CoreMotion/CoreMotion.h>
#import "NSDate+helper.h"
#import "Utilities.h"

static NSInteger numberTotal = 10000;

@interface TodayViewController ()
@property (nonatomic, weak) IBOutlet UILabel *lblTitle;
@property (weak, nonatomic) IBOutlet CircleProgressBar *circleProgressToday;
@property (weak, nonatomic) IBOutlet UILabel *lblValueStep;
@property (weak, nonatomic) IBOutlet UILabel *lblTotalStep;
@property (weak, nonatomic) IBOutlet UILabel *lblRemainingStep;
@property (weak, nonatomic) IBOutlet UILabel *lblTotalStepOther;
@property (weak, nonatomic) IBOutlet UILabel *lblRemainingStepOther;
@property (weak, nonatomic) IBOutlet UILabel *lblPercent;

@property (nonatomic, strong) CMPedometer *pedometer;
@property (nonatomic, strong) CMMotionActivityManager *motionActivityManager;
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) BOOL isRequesting;
@end

@implementation TodayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.lblTitle.text = NSLocalizedString(@"lifelog.today.title", nil);
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.lblTitle attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    
    if ([CMPedometer isStepCountingAvailable]) {
        _pedometer = [[CMPedometer alloc] init];
    }
    if ([CMMotionActivityManager isActivityAvailable]) {
        _motionActivityManager = [[CMMotionActivityManager alloc] init];
    }
    self.isRequesting = NO;
    if (_targetStep <= 0) {
        _targetStep = numberTotal;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(countStep) userInfo:nil repeats:YES];
    [_timer fire];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_timer invalidate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IBAction
- (IBAction)menuButtonTouchUpInside:(id)sender
{
    
}

- (IBAction)backButtonTouchUpInside:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)buttonShareTouchUpInside:(id)sender {
    
}

- (IBAction)buttonFacebookTouchUpInside:(id)sender {
    NSString * content = @"Finish 500 steps";
    TodayViewController __weak *weakSelf = self;
    [Utilities shareFacebook:content withViewController:weakSelf];
}

- (IBAction)buttonLineTouchUpInside:(id)sender {
    NSString * content = @"Finish 500 steps";
    TodayViewController __weak *weakSelf = self;
    [Utilities shareLine:content withViewController:weakSelf];
}

#pragma mark - Functions Private
- (void)countStep
{
    if (self.isRequesting == YES) {
        return;
    }
    if ([CMMotionActivityManager isActivityAvailable]) {
        self.isRequesting = YES;
        NSDate *endDate = [NSDate date];
        NSDate *startDate = [endDate beginningAtMidnightOfDay];
        TodayViewController __weak *weakSelf = self;
        dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL);
        dispatch_async(myQueue, ^{
            if (weakSelf == nil) {
                return ;
            }
            [weakSelf.pedometer queryPedometerDataFromDate:startDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
                NSInteger numberStep = [pedometerData.numberOfSteps integerValue];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf updateStepUI:numberStep];
                });
            }];
        });
    }
}

- (void)updateStepUI:(NSInteger)numberStep
{
    // NSLog(@"Number of step: %ld", numberStep);
    self.isRequesting = NO;
    float valueProgress = numberStep*1.f/_targetStep;
    [self.circleProgressToday setProgress:valueProgress animated:YES];
    self.lblValueStep.text = [Utilities addCommaFromNumber:numberStep];
    self.lblTotalStep.text = [NSString stringWithFormat:@"/ %@", [Utilities addCommaFromNumber:_targetStep]];
    self.lblRemainingStep.text = [NSString stringWithFormat:@"%@%ld%@", NSLocalizedString(@"lifelog.today.remaining.step.1", nil), (_targetStep - numberStep), NSLocalizedString(@"lifelog.today.remaining.step.2", nil)];
    self.lblTotalStepOther.text = [NSString stringWithFormat:@"%@%@%@", NSLocalizedString(@"lifelog.today.total.other", nil), [Utilities addCommaFromNumber:_targetStep], NSLocalizedString(@"lifelog.today.unit.step", nil)];
    self.lblRemainingStepOther.text = [NSString stringWithFormat:@"%@%ld%@", NSLocalizedString(@"lifelog.today.remaining.other", nil), (_targetStep - numberStep), NSLocalizedString(@"lifelog.today.unit.step", nil)];
    self.lblPercent.text = [NSString stringWithFormat:@"%@%i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(numberStep*100/_targetStep), NSLocalizedString(@"lifelog.today.percent", nil)];
}

@end
