//
//  HomeHubUpdateStartViewController.m
//  OneCable
//
//  Created by nComz on 2017. 5. 11..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "HomeHubUpdateStartViewController.h"
#import "HomeHubUpdateCompleteViewController.h"
#import "RequestHandler.h"

@interface HomeHubUpdateStartViewController () {
    
    BOOL endUpgrade;
    NSTimer *_timer;
    NSInteger _elapsedSeconds;
}

@end

@implementation HomeHubUpdateStartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    endUpgrade = NO;
    
    _imgvLoading.hidden = YES;
    _btnConfirm.enabled = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self startLoading:YES];
    
    switch (_updateType) {
        case 1: //전체
        {
            [self requestHubFirmwareUpgrade];
        }
            break;
        case 2: //펌웨어
        {
            [self requestHubFirmwareUpgrade];
        }
            break;
        case 3: //소프트웨어
        {
            [self requestHubSoftwareUpgrade];
        }
            break;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)startLoading:(BOOL)isStart {
    
    //    _lblTimer.hidden = !isStart;
    _imgvLoading.hidden = !isStart;
    
    if (isStart) {
        
        _elapsedSeconds = kMaxTimeOut;
        //        _lblTimer.text = [NSString stringWithFormat:@"%zd", _elapsedSeconds];
        if (!_timer) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateInclusionStatus) userInfo:nil repeats:YES];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if ([_imgvLoading.layer animationForKey:@"SpinAnimation"] == nil) {
                CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
                animation.fromValue = [NSNumber numberWithFloat:0.0f];
                animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
                animation.duration = 2.0f;
                animation.repeatCount = INFINITY;
                [_imgvLoading.layer addAnimation:animation forKey:@"SpinAnimation"];
            }
        });
    }
    else {
        
        _elapsedSeconds = kMaxTimeOut;
        
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
        
        if ([_imgvLoading.layer animationForKey:@"SpinAnimation"] != nil) {
            [_imgvLoading.layer removeAnimationForKey:@"SpinAnimation"];
        }
    }
}

- (void)updateInclusionStatus {
    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        
        _elapsedSeconds--;
        if (_elapsedSeconds == 0) {
            
        }
    });
}




#pragma mark - User Event
- (IBAction)btnConfirmTouched:(id)sender {
    
}




//#define  MSG_TYPE_FIRMWARE_UPGRADE          @"firmware.upgrade"
//#define  MSG_TYPE_FIRMWARE_UPGRADE_RESULT   @"firmware.upgrade.result"
//#define  MSG_TYPE_SOFTWARE_UPGRADE          @"software.upgrade"
//#define  MSG_TYPE_SOFTWARE_UPGRADE_RESULT   @"software.upgrade.result"
//#define  MSG_TYPE_NODES_RELOAD              @"nodes.reload"


#pragma mark - SocketService
//자동로그인 요청
- (void)requestAutoLogin {;
    
    LoginModel *tmpInfo = [[LoginModel alloc] init];
    tmpInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
    tmpInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_AUTO_LOGIN];
    NSDictionary *param = @{@"Authorization": tmpInfo.authorization,
                            @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
                            @"os_type": MOBILE_DEVICE_TYPE};
    
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[LoginModel class] isLoading:YES];
}

-(void)requestHubFirmwareUpgrade {
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_FIRMWARE_UPGRADE];
    NSDictionary *param = @{@"device_id":_hubInfo.deviceId,
                            @"cust_id": [[JDFacade facade].loginUser custId],
                            @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[SoKDeviceWorkModel class] isLoading:YES];
}

-(void)requestHubSoftwareUpgrade {
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_SOFTWARE_UPGRADE];
    NSDictionary *param = @{@"device_id":_hubInfo.deviceId,
                            @"cust_id": [[JDFacade facade].loginUser custId],
                            @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[SoKDeviceWorkModel class] isLoading:YES];
}


- (void)failSocket:(NSString*)messageType {
    
    [[JDFacade facade] confirmTitle:@"홈허브 업데이트 실패"
                            message:@"오류가 발생하여 홈허브 업데이트가 완료되지 않았습니다."
                         btnOKLabel:@"재시도"
                     btnCancelLabel:@"취소"
                         completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                             
                             if (buttonIndex == 0) { //재시도
                                 
                                 [self startLoading:YES];
                                 
                                 if (EQUALS(messageType, MSG_TYPE_FIRMWARE_UPGRADE_RESULT))
                                     [self requestHubFirmwareUpgrade];
                                 else
                                     [self requestHubFirmwareUpgrade];
                                 
                             }
                             else {
                                 
                                 [self.navigationController popToRootViewControllerAnimated:YES];
                             }
                         }];
}

#pragma mark - SocketService
- (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result {
    
    
    SWITCH(result.messageType)
    {
        CASE(MSG_TYPE_AUTO_LOGIN)
        {
            if (result.isSuccess) {
                
                LoginModel *loginInfo = (LoginModel *)message;
                loginInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
                loginInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
                
                [self actionForLoginSucceed:loginInfo];
            }
            else {
                
                [[JDFacade facade] alertTitle:@"알림" message:result.resultMsg];
            }
            
            break;
        }
        CASE(MSG_TYPE_FIRMWARE_UPGRADE)
        CASE(MSG_TYPE_SOFTWARE_UPGRADE)
        {
            if (!result.isSuccess) {
                
                [self startLoading:NO];
                
                [self failSocket:result.messageType];
            }
        
        }
        DEFAULT
        {
            break;
        }
    }
}

-(void) receiveSocketData:(NSNotification *)notification {
    
    SoKDeviceWorkModel *result = [[SoKDeviceWorkModel alloc] initWithDictionary:notification.object error:nil];
    NSLog(@"receiveSocketData Result : %@", result);
    
    [self startLoading:NO];
    
    //오류
    //    업그레이드 결과(실패:fail, 성공:success, 타임아웃:timeout)
    if (EQUALS(result.work_result, @"fail") || EQUALS(result.work_result, @"timeout")) {

        [self failSocket:result.messageType];
        
    }
    else if ([result.messageType isEqualToIgnoreCase:MSG_TYPE_FIRMWARE_UPGRADE_RESULT]) {
        
        if (_updateType == 1) {
            
            //끝
            [self requestAutoLogin];
            //[self moveUpdateComplete];
        }
        else {
            
            [self startLoading:YES];
            [self requestHubSoftwareUpgrade];
        }
    }
    else if ([result.messageType isEqualToIgnoreCase:MSG_TYPE_SOFTWARE_UPGRADE_RESULT]) {

        //유저 정보 업데이트
        [self requestAutoLogin];
    }

}





//로그인 이후 처리.
- (void)actionForLoginSucceed:(LoginModel *)loginInfo {
    
    if (loginInfo) {//API 성공함
        
        [JDFacade facade].loginUser = loginInfo;
        
        NSLog(@"loginUser : %@", [JDFacade facade].loginUser);
        
        if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].tmpEmailId]) {
            [JDFacade facade].tmpEmailId = ksEmptyString;
        }
        
        if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].loginUser.newEmailId]) {//이메일 변경 요청 중
            [JDFacade facade].loginUser.newEmailId = ksEmptyString;
        }
        
        [RequestHandler handler].authorization = loginInfo.authorization;
        
        //다음 이동
        [self moveUpdateComplete];
        
    }
}


- (void)moveUpdateComplete {
    
    HomeHubUpdateCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubUpdateCompleteViewController" storyboardName:@"HomeHub"];;
    vc.isUpdate = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}

@end
