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

#import "HistoryViewController.h"
#import "Utilities.h"
#import "ServerAPI.h"

#import "HistoryListTableViewCell.h"

@interface HistoryViewController ()

@end

@implementation HistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.bottomLayoutGuide attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.viewCollectionMode attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.viewHeader attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    // Do any additional setup after loading the view from its nib.
//    self.title = NSLocalizedString(@"lifelog.history.title", nil);
    
    _isDisableLoadMore = true;
    
    [self setupView];
    [self setupChartView];
    
    _startDate = [NSDate date];
    _endDate   = _startDate;
    
    self.lblDatetime.text = [Utilities stringFromDate:_endDate withFormat:@"YYYY年MM月dd日 EEEE" locale:@"ja_JP"];
    
    //register nib for table view
    [self.tableBase registerNib:[UINib nibWithNibName:@"HistoryListTableViewCell" bundle:nil] forCellReuseIdentifier:@"HistoryListCell"];
}

- (void)viewDidAppear:(BOOL) animated
{
    [super viewDidAppear:animated];
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, 400);
    [self.scrollView setNeedsLayout];
    [self.scrollView setNeedsUpdateConstraints];
    [self checkRequestData];
}

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

- (void)setupView {
    NSArray *typeTitle = [NSArray arrayWithObjects:NSLocalizedString(@"lifelog.history.type.1", nil), NSLocalizedString(@"lifelog.history.type.2", nil), NSLocalizedString(@"lifelog.history.type.3", nil), NSLocalizedString(@"lifelog.history.type.4", nil), NSLocalizedString(@"lifelog.history.type.5", nil), nil];
    [self.viewCollectionType setButtonNumber:typeTitle.count];
    [self.viewCollectionType setSpacing:2];
    [self.viewCollectionType setArrayTitle:typeTitle];
    self.viewCollectionType.changeCurrentIndex = ^(int index){
        [self changeDate];
    };
    
    NSArray *modeTitle = [NSArray arrayWithObjects:NSLocalizedString(@"lifelog.history.mode.1", nil), NSLocalizedString(@"lifelog.history.mode.2", nil), NSLocalizedString(@"lifelog.history.mode.3", nil), nil];
    [self.viewCollectionMode setButtonNumber:modeTitle.count];
    [self.viewCollectionMode setSpacing:0];
    [self.viewCollectionMode setSelectedIndex:1];
    [self.viewCollectionMode setCornerRadius:0];
    [self.viewCollectionMode setNormalColor:[Utilities convertHecToColor:0x191919] highlightColor:[Utilities convertHecToColor:0x474747] textColor:[UIColor whiteColor]];
    [self.viewCollectionMode setArrayTitle:modeTitle];
    self.viewCollectionMode.changeCurrentIndex = ^(int index){
        if(self.tableBase.alpha == 0.0) {
            [self updateView];
        }
        else {
            NSArray * list = [_curListArray objectAtIndex:index];
            [self updateTableData:list error:nil];
        }
    };
    
    NSArray *shareTitle = [NSArray arrayWithObjects:@"icon_facebook", @"icon_twitter", @"icon_line", @"icon_mail", @"icon_other_send", nil];
    [self.viewCollectionShare setButtonNumber:typeTitle.count];
    [self.viewCollectionShare setSpacing:3];
    [self.viewCollectionShare setArrayTitle:shareTitle];
    [self.viewCollectionShare disableSelection];
    [self.viewCollectionShare enableImageIcon];
    //add tap gesture for enable tap on gesture on CollectionView in ScrollView
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureAction:)];
    [recognizer setNumberOfTapsRequired:1];
    self.scrollView.userInteractionEnabled = YES;
    [self.scrollView addGestureRecognizer:recognizer];
}

- (void)setupChartView {
    self.viewBarChart.chartDescription.enabled = NO;
    self.viewBarChart.leftAxis.drawGridLinesEnabled = NO;
    self.viewBarChart.rightAxis.drawGridLinesEnabled = NO;
    self.viewBarChart.legend.enabled = NO;

    ChartXAxis *xAxis = self.viewBarChart.xAxis;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.drawGridLinesEnabled = NO;
    xAxis.drawAxisLineEnabled = NO;
    xAxis.drawLabelsEnabled = YES;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.labelFont = [UIFont systemFontOfSize:10.f];
    xAxis.labelTextColor = [UIColor whiteColor];
    xAxis.granularity = 1.0; // only intervals of 1 day
    xAxis.labelCount = 8;
    
    self.viewBarChart.leftAxis.drawAxisLineEnabled = NO;
    self.viewBarChart.rightAxis.drawAxisLineEnabled = NO;
}

-(void) updateView {
    HistoryObject * obj = [_curHisArray objectAtIndex:self.viewCollectionMode.getCurrentIndex];
    self.lblStep.text = [NSString stringWithFormat:@"%d step", obj.target];
    self.lblCircleStep.text = [NSString stringWithFormat:@"%d step", obj.step];
    self.lblRemaining.text = [NSString stringWithFormat:@"%d step", obj.missing];
    self.lblCircleRemain.text = [NSString stringWithFormat:@"目標まであと\n%d stepです", obj.missing];
    self.lblPercent.text = [NSString stringWithFormat:@"%0.2f%%", obj.percent];
    self.lblCalories.text = [NSString stringWithFormat:@"%0.2f kcal", obj.calories];
    self.lblDistance.text = [NSString stringWithFormat:@"%0.1f KM", obj.distance];
    self.lblTime.text = [Utilities convertSecondToShortTime:obj.time];
    [self updateGraphView];
}

-(void) updateGraphView {
    HistoryObject * obj = [_curHisArray objectAtIndex:self.viewCollectionMode.getCurrentIndex];

    NSMutableArray *yVals = [[NSMutableArray alloc] init];
    for (int i = 0; i < obj.dataGraph.count; i++)
    {
        [yVals addObject:[[BarChartDataEntry alloc] initWithX:i y:[[obj.dataGraph objectAtIndex:i] doubleValue]]];
    }
    
    BarChartDataSet *set1 = nil;
    if (self.viewBarChart.data.dataSetCount > 0)
    {
        set1 = (BarChartDataSet *)self.viewBarChart.data.dataSets[0];
        set1.values = yVals;
        
        NSMutableArray *color = [[NSMutableArray alloc] init];
        for(int i = 0; i < yVals.count; i++) {
            BarChartDataEntry *en = yVals[i];
            if(obj.step != 0) {
                double percent = en.y / obj.step * 100;
                if(percent > 80) {
                    [color addObject:[UIColor redColor]];
                }
                else if(percent > 60) {
                    [color addObject:[UIColor yellowColor]];
                }
                else {
                    [color addObject:[UIColor whiteColor]];
                }
            }
            else {
                [color addObject:[UIColor whiteColor]];
            }
        }
        [set1 setColors:color];
        
        [self.viewBarChart.data notifyDataChanged];
        [self.viewBarChart notifyDataSetChanged];
    }
    else
    {
        set1 = [[BarChartDataSet alloc] initWithValues:yVals label:@""];
        
        NSMutableArray *color = [[NSMutableArray alloc] init];
        for(int i = 0; i < yVals.count; i++) {
            BarChartDataEntry *en = yVals[i];
            if(obj.step != 0) {
                double percent = en.y / obj.step * 100;
                if(percent > 80) {
                    [color addObject:[UIColor redColor]];
                }
                else if(percent > 60) {
                    [color addObject:[UIColor yellowColor]];
                }
                else {
                    [color addObject:[UIColor whiteColor]];
                }
            }
            else {
                [color addObject:[UIColor whiteColor]];
            }
        }
        [set1 setColors:color];
        NSMutableArray *dataSets = [[NSMutableArray alloc] init];
        [dataSets addObject:set1];
        
        BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
        data.barWidth = 0.5f;
        
        self.viewBarChart.data = data;
    }
}

-(void) checkRequestData {
    if(self.tableBase.alpha == 0.0) {
        NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken];
        MBProgressHUD *hudView = [MBProgressHUD showHUDAddedTo:self.view animated:true];
        [[ServerAPI server] requestHistory:token startDate:_startDate endDate:_endDate CompletionHandler:^(NSArray *array, NSError *error) {
            HistoryViewController __weak *weakSelf = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                if(hudView != nil) {
                    [hudView hideAnimated:true];
                }
            });
            if(error == nil) {
                _curHisArray = array;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf updateView];
                });
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *message = [error.userInfo objectForKey:@"message"];
                    [Utilities showErrorMessage:message withViewController:weakSelf];
                });
            }
        }];
    }
    else {
        [self resetData];
    }
}

-(void) callRequestToUpdateData {
    [super callRequestToUpdateData];
    NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken];

    MBProgressHUD *hudView = nil;
    if(_curPage == 1 && !self.refreshControl.isRefreshing) {
        hudView = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    }
    [[ServerAPI server] requestHistoryList:token startDate:_startDate endDate:_endDate CompletionHandler:^(NSArray *array, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(hudView != nil) {
                [hudView hideAnimated:true];
            }
        });
        HistoryViewController __weak *weakSelf = self;
        if(error == nil) {
            _curListArray = array;
            NSArray * list = [array objectAtIndex:weakSelf.viewCollectionMode.getCurrentIndex];
            [weakSelf updateTableData:list error:error];
        }
        else {
            [weakSelf updateTableData:array error:error];
        }
    }];
}

- (void) changeDate {
    switch (self.viewCollectionType.getCurrentIndex) {
        case 1:
            _startDate = [_endDate dateByAddingTimeInterval:-86400 * 7];
            break;
        case 2:
            _startDate = [_endDate dateByAddingTimeInterval:-86400 * 30];
            break;
        case 3:
            _startDate = [_endDate dateByAddingTimeInterval:-86400 * 30 * 3];
            break;
        case 4:
            _startDate = [_endDate dateByAddingTimeInterval:-86400 * 30 * 6];
            break;
        default:
            _startDate = _endDate;
            break;
    }
    if(_startDate == _endDate) {
        self.lblDatetime.text = [Utilities stringFromDate:_endDate withFormat:@"YYYY年MM月dd日 EEEE" locale:@"ja_JP"];
    }
    else {
        NSString * startDateString = [Utilities stringFromDate:_startDate withFormat:@"YYYY年MM月dd日" locale:@"ja_JP"];
        NSString * endDateString = [Utilities stringFromDate:_endDate withFormat:@"YYYY年MM月dd日" locale:@"ja_JP"];
        self.lblDatetime.text = [NSString stringWithFormat:@"%@-%@", startDateString, endDateString];
    }
    [self checkRequestData];
}

#pragma mark IBAction
-(void) swipeAction:(UISwipeGestureRecognizer *)sender {
    bool alphaValue = self.scrollView.alpha == 1.0 ? 1.0 : 0.0;
    [UIView animateWithDuration:0.5 animations:^{
        self.tableBase.alpha = alphaValue;
        self.scrollView.alpha = 1.0 - alphaValue;
    } completion:^(BOOL completed) {
        [self checkRequestData];
    }];
}

- (IBAction)clickBackward:(UIButton *)sender {
    _endDate = [_endDate dateByAddingTimeInterval:-86400];
    [self changeDate];
}

- (IBAction)clickForward:(UIButton *)sender {
    _endDate = [_endDate dateByAddingTimeInterval:86400];
    [self changeDate];
}

-(void)gestureAction:(UITapGestureRecognizer *) sender
{
    CGPoint touchLocation = [sender locationOfTouch:0 inView:self.viewCollectionShare];
    NSIndexPath *indexPath = [self.viewCollectionShare.collectionView indexPathForItemAtPoint:touchLocation];
    NSString * content = @"Finish 500 steps";
    HistoryViewController __weak *weakSelf = self;
    if(indexPath != NULL) {
        switch (indexPath.row) {
            case 0: //share facebook
                [Utilities shareFacebook:content withViewController:weakSelf];
                break;
            case 1: //share twitter
                [Utilities shareTwitter:content withViewController:weakSelf];
                break;
            case 2 : //share line
                [Utilities shareLine:content withViewController:weakSelf];
                break;
            case 3: // share email
                [Utilities shareEmail:content withViewController:weakSelf];
                break;
            default: //share other
                [Utilities shareOther:content withViewController:weakSelf];
                break;
        }
    }
}

#pragma mark UITableView Delegate
-  (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HistoryListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryListCell"];
    HistoryObject * obj = [_curDataList objectAtIndex:indexPath.row];
    cell.lblTitle.text = [Utilities stringFromDate:obj.date withFormat:@"dd日 (EEEE)" locale:@"ja_JP"];
    cell.lblStep.text = [NSString stringWithFormat:@"%d", obj.step];
    cell.lblDiff.text = [NSString stringWithFormat:@"%d", obj.step_diff];
    cell.imgArrow.image = (obj.step_diff > 0) ? [UIImage imageNamed:@"arrow_incre"] : [UIImage imageNamed:@"arrow_decre"];
    cell.lblPower.text = [NSString stringWithFormat:@"%0.2f", obj.calories];
    cell.lblDistance.text = [NSString stringWithFormat:@"%0.1f", obj.distance];
    cell.lblDuration.text = [Utilities convertSecondToShortTime:obj.time];
    return cell;
}

@end
