HomeViewController.m 13.9 KB
//
//  HomeViewController.m
//  LifeLog
//
//  Created by Nguyen Van Phong on 7/25/17.
//  Copyright © 2017 PhongNV. All rights reserved.
//

#import "HomeViewController.h"
#import "NSDate+helper.h"
#import <CoreMotion/CoreMotion.h>
#import "CMMotionActivityExtra.h"
#import "TodayViewController.h"
#import "Utilities.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "ServerAPI.h"

static NSInteger numberTotal = 10000;

@interface HomeViewController ()
{
    MBProgressHUD *progressHud;
}
@property (nonatomic, weak) IBOutlet UILabel *lblTitle;
@property (nonatomic, weak) IBOutlet UIImageView *avatar;
@property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent;
@property (nonatomic, weak) IBOutlet UILabel *lblValueStep;
@property (nonatomic, weak) IBOutlet UILabel *lblUnitStep;
@property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther;
@property (nonatomic, weak) IBOutlet UILabel *lblPercent;
@property (nonatomic, weak) IBOutlet UILabel *lblNotice;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome;

@property (nonatomic, strong) CMPedometer *pedometer;
@property (nonatomic, strong) CMMotionActivityManager *motionActivityManager;
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger bike;
@property (nonatomic, assign) NSInteger walking;
@property (nonatomic, assign) NSInteger running;
@property (nonatomic, strong) NSDate *dateCurrent;

//@property (nonatomic, assign) BOOL isRequesting;
@property (nonatomic, assign) int totalRequest;
@property (nonatomic, assign) int countComplete;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil);
  
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.lblTitle attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
  
    self.avatar.backgroundColor = [UIColor whiteColor];
    self.avatar.layer.borderWidth = 2.0f;
    self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f;
    self.avatar.layer.masksToBounds = YES;
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser];
    User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
    if (user != nil) {
        NSString *linkImage = [NSString stringWithFormat:@"%@%@", kServerAddress, user.profile_image];
        NSURL *urlImage = [NSURL URLWithString:linkImage];
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        sessionConfig.timeoutIntervalForRequest = 30.0;
        sessionConfig.timeoutIntervalForResource = 60.0;
        sessionConfig.HTTPMaximumConnectionsPerHost = 20;
        sessionConfig.allowsCellularAccess = YES;
        HomeViewController __weak *weakSelf = self;
        NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
        NSURLSessionDataTask *downloadPhotoTask = [session
                                                   dataTaskWithURL:urlImage completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                       if (weakSelf == nil)
                                                       {
                                                           return;
                                                       }
                                                       if (error == nil) {
                                                           UIImage *image = [[UIImage alloc] initWithData:data];
                                                           [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                                               weakSelf.avatar.image = image;
                                                           }];
                                                       }
                                                   }];
        [downloadPhotoTask resume];
    }
    
    self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil);
    
    _dateCurrent = [NSDate date];
    self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)];
    
    self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil);
  
    if ([CMPedometer isStepCountingAvailable]) {
        _pedometer = [[CMPedometer alloc] init];
    }
    if ([CMMotionActivityManager isActivityAvailable]) {
        _motionActivityManager = [[CMMotionActivityManager alloc] init];
    }
    _operationQueue = [[NSOperationQueue alloc] init];
    _bike = 0;
    _walking = 0;
    _running = 0;
    _segmentHome.selectedSegmentIndex = 1;
//    _isRequesting = NO;
    _totalRequest = 0;
    _countComplete = 0;
    
    progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    progressHud.mode = MBProgressHUDModeIndeterminate;
    progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    _timer = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(countStep) userInfo:nil repeats:YES];
//    [_timer fire];
    [self countStep];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [dateFormatter stringFromDate:_dateCurrent];
    
    HomeViewController __weak *weakSelf = self;
    [[ServerAPI server] requestTopWithMode:(int)_segmentHome.selectedSegmentIndex andDate:dateString CompletionHandler:^(TopObject *topObject, NSError *error) {
        if(weakSelf == nil) {
            return ;
        }
        if (error == nil) {
            NSLog(@"TopObject: %@", topObject);
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *message = [error.userInfo objectForKey:@"message"];
                [Utilities showErrorMessage:message withViewController:weakSelf];
            });
        }
    }];
}

- (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)todayButtonTouchUpInside:(id)sender
{
    TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil];
    [self.navigationController pushViewController:todayVC animated:YES];
}

- (IBAction)leftButtonTouchUpInside:(id)sender
{
    self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)];
    self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)];
    [self countStep];
}

- (IBAction)rightButtonTouchUpInside:(id)sender
{
    self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60];
    self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)];
    [self countStep];
}

- (IBAction)segmentValueChange:(id)sender {
    [self updateStepUI];
}

#pragma mark - Functions Private
- (void)countStep
{
//    if (self.isRequesting == YES) {
//        return;
//    }
    if ([CMMotionActivityManager isActivityAvailable]) {
        [progressHud showAnimated:YES];
        [progressHud setHidden:NO];
        // self.isRequesting = YES;
        self.bike = 0;
        self.walking = 0;
        self.running = 0;
        NSDate *startDate = [self.dateCurrent beginningAtMidnightOfDay];
        NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)];
    
        HomeViewController __weak *weakSelf = self;
        dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL);
        dispatch_async(myQueue, ^{
            if (weakSelf == nil) {
                return ;
            }
            
            [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) {
                if (error || activities.count <= 0) {
                    weakSelf.totalRequest = 0;
                    weakSelf.countComplete = 0;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf updateStepUI];
                    });
                    return ;
                }
                // set EndDate
                weakSelf.totalRequest = (int)activities.count;
                NSMutableArray *arrayActivities = [[NSMutableArray alloc] init];
                for (int i = 0; i < activities.count; i++) {
                    CMMotionActivity *activity = [activities objectAtIndex:i];
                    CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init];
                    activityExtra.activity = activity;
                    if (i == activities.count - 1) {
                        activityExtra.endDate = endDate;
                    }
                    else {
                        CMMotionActivity *activityNext = [activities objectAtIndex:i+1];
                        activityExtra.endDate = activityNext.startDate;
                    }
                    [arrayActivities addObject:activityExtra];
                }
                
                for (CMMotionActivityExtra *activityExtra in arrayActivities) {
                    // NSLog(@"%@", activityExtra.activity.startDate);
                    [weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
                        NSInteger numberStep = [pedometerData.numberOfSteps integerValue];
                        
                        if (activityExtra.activity.cycling) {
                            // self.bike
                            weakSelf.bike += numberStep;
                            //NSLog(@"Step cycling");
                        }
                        else if (activityExtra.activity.walking) {
                            // self.walking
                            weakSelf.walking += numberStep;
                            //NSLog(@"Step walking");
                        }
                        else if (activityExtra.activity.running) {
                            weakSelf.running += numberStep;
                            //NSLog(@"Step running");
                        }
                        else {
                            // unknown
                            //NSLog(@"Step unknown");
                        }
                        // NSLog(@"Number of step--> %ld", numberStep);
                        weakSelf.countComplete += 1;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf updateStepUI];
                        });
                    }];
                }
                // NSLog(@"-----------------------------------------------------");
            }];
        });
    }
    else {
        [progressHud setHidden:YES];
    }
}

- (void)updateStepUI //:(NSInteger)numberStep
{
    if (self.totalRequest == self.countComplete) {
        switch (self.segmentHome.selectedSegmentIndex) {
            case 0:
                self.lblValueStep.text = [Utilities addCommaFromNumber:self.bike];
                self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.bike];
                self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.bike*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
                break;
                
            case 1:
                self.lblValueStep.text = [Utilities addCommaFromNumber:self.walking];
                self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.walking];
                self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.walking*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
                break;
                
            case 2:
                self.lblValueStep.text = [Utilities addCommaFromNumber:self.running];
                self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.running];
                self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.running*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
                break;
                
            default:
                break;
        }
        // NSLog(@"Walking: %ld || Running: %ld || Bike: %ld", self.walking, self.running, self.bike);
        // self.isRequesting = NO;
        self.countComplete = 0;
        self.totalRequest = 0;
        [progressHud setHidden:YES];
    }
}

@end