//
//  HomeModeUpdateViewController.m
//  
//
//  Created by Jason Lee on 10/30/15.
//
//
#import "JDObject.h"

#import "CustomButton.h"
#import "CustomLabel.h"
#import "CustomImageView.h"

#import "RequestHandler.h"
#import "JDJSONModel.h"

#import "HomeModeUpdateViewController.h"
#import "ModeModel.h"
#import "DeviceSelectPopupView.h"
#import "HomeModeSettingsViewController.h"
#import "UIImageView+WebCache.h"


@interface HomeModeUpdateViewController () {
    NSTimer *_modeChangePollingTimer;
    NSDate *_requestTime;
}
@end


#pragma mark - Class Definition

@implementation HomeModeUpdateViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    
    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    
    NSString *message = nil, *highlightMessage = nil;
    NSString *btnTitle = nil;
    if ([_mode.basicModeCode isEqualToString:HOME_MODE_HOME]) {
        btnTitle = @"귀가";
        highlightMessage = @"잘 돌아왔어요!";
        message = @"쾌적한 귀가모드를 \r실행할까요?";
        
    } else if ([_mode.basicModeCode isEqualToString:HOME_MODE_AWAY]) {
        btnTitle = @"외출";
        highlightMessage = @"안녕히 다녀오세요!";
        message = @"안전한 외출모드를 \r실행할까요?";
        
    } else if ([_mode.basicModeCode isEqualToString:HOME_MODE_MORNING]) {
        btnTitle = @"기상";
        highlightMessage = @"좋은 아침!";
        message = @"상쾌한 기상모드를\r실행할까요?";
        
    } else if ([_mode.basicModeCode isEqualToString:HOME_MODE_NIGHT]) {
        btnTitle = @"취침";
        highlightMessage = @"잘 자요!";
        message = @"편안한 취침모드를 \r실행할까요?";
        
    }
    
    //mode status check
    //일반 멤버 - 설정버튼 감춤, 홈그룹 씬아이디가 있을 경우, 노출 안함
    
    if ([JDFacade facade].loginUser.level < 90) {
        _tooltip.hidden = _btnSetting.hidden = YES;
    } else {
        _tooltip.hidden = (_mode.homegrpSceneId && ![_mode.homegrpSceneId isEmptyString]);
    }
    
    if (!_lblTooltip.hidden && _mode.deleteCnt && [_mode.deleteCnt integerValue] > 0) {
        _lblTooltip.text = @"삭제된 장치를\r정리하세요";
    }
    
    [_btnExecute setTitle:btnTitle forState:UIControlStateNormal];
    _lblMessage.text = [NSString stringWithFormat:@"%@\n\n%@", highlightMessage, message];
    [_lblMessage setFontSize:kUIFontSize01 text:_lblMessage.text];
    
//    [_lblMessage setColor:kUITextColor02 text:highlightMessage];
//    [_lblMessage setFontSize:kUIFontSize03 text:highlightMessage];
    
    [_imgvMode sd_setImageWithURL:[NSURL URLWithString:_mode.imageFileViewName] placeholderImage:nil options:SDWebImageRefreshCached];
}

- (void)prepareViewDidLoad {
    
}

#pragma mark - Main Logic

- (void)requestChangeHomeMode {

    NSString *modeTitle = [NSString stringWithFormat:@"%@ 모드", _mode.modeName];
    _lblMessage.text = [NSString stringWithFormat:@"%@\r\r실행 중입니다", modeTitle];
    
    [_lblMessage setFontSize:kUIFontSize01 text:_lblMessage.text];
    [_lblMessage setColor:kUITextColor01 text:_lblMessage.text];
    
    [_lblMessage setColor:kUITextColor02 text:modeTitle];
    [_lblMessage setFontSize:kUIFontSize03 text:modeTitle];
    
    //    NSString *path = [NSString stringWithFormat:API_PUT_DASHBOARD_MODE_CHANGE, _mode.modeId];
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_PUT_DASHBOARD_MODE_CHANGE arguments:nil];

    
    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestPUT parameters:nil modelClass:[JDJSONModel class] showLoadingView:NO completion:^(id responseObject) {
        if ([[JDFacade facade].currentViewController isEqual:self]) {
            
            //check requet done,
            _requestTime = [NSDate systemDate];
            
            if (_mode.homegrpSceneId && ![_mode.homegrpSceneId isEmptyString]) {//제어할 장치가 있는 경우,
                [self requestPollingHomeModeChanges];
            } else {
                [self setContentsForComplete];
            }
        }
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (NSInteger)elapsedSecondsFromNow {
    NSInteger seconds = 0;
    
    if (_requestTime) {
        NSTimeInterval elapsed = [[NSDate systemDate] timeIntervalSinceDate:_requestTime];
        seconds = elapsed;
    }
    return seconds;
}

- (void)requestPollingHomeModeChanges {
    
    //every 3sec?
    NSString *path = [NSString stringWithFormat:API_GET_MODE_STATUS, _mode.modeId];
    
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
        ModeModel *response = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
                                                                       modelClass:[ModeModel class] showLoadingView:NO];
        if (response) {
            BOOL isRequestDone = [response.status boolValue];
            BOOL isOverTimeLimit = [self elapsedSecondsFromNow] > 10;
            
            if (isOverTimeLimit || isRequestDone) {
                [self releaseModeChangePollingTimer];
                _requestTime = nil;
                
                if (isRequestDone) {
                    [self setContentsForComplete];
                }
                
                if (isOverTimeLimit) {
                    [self setContentsForReset];
                }
            } else {
                if (!_modeChangePollingTimer) {
                    _modeChangePollingTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(requestPollingHomeModeChanges) userInfo:nil repeats:YES];
                }
            }
        }
    });
}

- (void)setContentsForComplete {
    
    //chagne button image
    [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear  animations:^{
        _btnExecute.transform = CGAffineTransformMakeRotation(0);
    } completion:^(BOOL finished) {
        
        NSString *highlightMessage = [NSString stringWithFormat:@"%@ 상태가 되었습니다.", _mode.modeName];
        _lblMessage.text = highlightMessage;
        
        [_lblMessage setColor:kUITextColor02 text:highlightMessage];
        [_lblMessage setFontSize:kUIFontSize03 text:highlightMessage];
        
        _btnExecute.userInteractionEnabled = YES;
        [_btnExecute setBackgroundImage:[UIImage imageNamed:@"img_homemode_bigbtn_sucsess_img"] forState:UIControlStateNormal];
        
        [_btnExecute addTarget:self action:@selector(btnExecuteComplete:) forControlEvents:UIControlEventTouchUpInside];
    }];
}

- (void)setContentsForReset {
    
    //chagne button image
    [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear  animations:^{
        _btnExecute.transform = CGAffineTransformMakeRotation(0);
    } completion:^(BOOL finished) {
        [self initUI];
        
        _btnExecute.userInteractionEnabled = YES;
        [_btnExecute setBackgroundImage:[UIImage imageNamed:@"img_homemode_bigbtn_default"] forState:UIControlStateNormal];
    }];
}


#pragma mark - UI Events

- (IBAction)btnExecuteTouched:(id)sender {
    
    _btnExecute.userInteractionEnabled = NO;
    [_btnExecute setBackgroundImage:[UIImage imageNamed:@"img_progress_big_s01"] forState:UIControlStateNormal];
    [_btnExecute setTitle:ksEmptyString forState:UIControlStateNormal];
    
    [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
        _btnExecute.transform = CGAffineTransformMakeRotation(M_PI);
    } completion:nil];
    
    [self requestChangeHomeMode];
}

- (void)btnExecuteComplete:(id)sender {
    [[JDFacade facade] gotoWishMenu:KNMenuIdDashboard];
}

- (IBAction)btnSettingTouched:(id)sender {
    HomeModeSettingsViewController *vc = (HomeModeSettingsViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"HomeModeSettingsViewController" storyboardName:@"Main"];
    vc.mode = _mode;
    
    [self presentViewController:vc animated:YES completion:nil];
}

- (IBAction)btnCloseTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - MemoryWarning
- (void)releaseModeChangePollingTimer {
    if (_modeChangePollingTimer) {
        [_modeChangePollingTimer invalidate];
        _modeChangePollingTimer = nil;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [self releaseModeChangePollingTimer];
}

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




@end
