//
//  ThingsAddIncludeViewController.m
//  kneet2
//
//  Created by Jason Lee on 11/13/15.
//  Copyright © 2015 ntels. All rights reserved.
//

#import "JDObject.h"

#import "RequestHandler.h"
#import "DeviceModel.h"

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

#import "ThingsAddIncludeViewController.h"
#import "ThingsAddFailViewController.h"
#import "ThingsAddCompleteViewController.h"


@interface ThingsAddIncludeViewController () {
    NSTimer *_timer;
    NSInteger _elapsedSeconds;
    
    CommandModel *_startCommand;
    CommandModel *_stopCommand;
}
@end
// 가스밸브 타이틀 : 가스 밸브 센서 추가
// 가스밸브 장치초기화 코멘트 : 밸브를 열림 상태에 두고 "위로" 버튼을 비프음이 날 때까지 5초 이상 누르세요.
// 가스밸브 이미지 명 : img_things_product_addimg_01_smartgasvalve_wait

// 도어센서 타이틀 : 도어 센서 추가
// 도어센서 장치초기화 코멘트 : 센서 아래 버튼을 1회 누른 후 LED가 깜빡임을 멈추면 1회 더 누르세요.
// 도어센서 이미지 명 : img_things_product_addimg_02_mutisensor_door_wait

// 스마트플러그 타이틀 : 스마트 플러그 추가
// 스마트플러그 장치초기화 코멘트 : 위에 버튼에 빨간 불이 깜빡일 때까지 5초 이상 누르세요.
// 스마트플러그 이미지 명 : img_things_product_addimg_03_smartplug_wait

#pragma mark - Class Definition

@implementation ThingsAddIncludeViewController


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


- (void)initUI {
    [self startLoading:NO];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        _maskView.alpha = 0.7;
    } completion:^(BOOL finished) {
        
        _constraintPopViewTop.constant = (IPHONE_HEIGHT - _popView.height) / 2;
        
        [UIView animateWithDuration:kfAnimationDur animations:^{
            [self.view layoutIfNeeded];
        }];
    }];
}

- (void)prepareViewDidLoad {
//    if (_addableDevice) {
//        _lblDesc.text = [NSString stringWithFormat:@"%@의\n00 버튼을\n00 누르세요", _addableDevice[@"deviceName"]];
//        [self requestIncludeDevice:YES];
//    } else if (_removableDevice) {
//        _lblDesc.text = [NSString stringWithFormat:@"%@의\n00 버튼을\n00 누르세요", _removableDevice.deviceName];
//        [self requestExcludeDevice:YES];
//    }
    _lblTitle.text = [NSString stringWithFormat:@"%@ 추가", _addDevice.prdName];
    _imgThings.image = [_addDevice imgaeForAddDel];
    _lblDesc.text = [_addDevice manufacturerName];
    [self requestIncludeDevice:YES];
}

#pragma mark - Main Logic
- (void)requestIncludeDevice:(BOOL)isStart {
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_DEVICE_COMMAND];

    NSDictionary *param = @{@"device_id": [[JDFacade facade].loginUser isMultiHomeHub] ? _selectHub.deviceId:[[JDFacade facade].loginUser getHomeHubID],
                            @"command_type":isStart? CMD_TYPE_PAIRING_START:CMD_TYPE_PAIRING_STOP,
                            @"cust_id": [[JDFacade facade].loginUser custId],
                            @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[CommandModel class]];
}

- (void)requestExcludeDevice:(BOOL)isStart {
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_DEVICE_COMMAND];
    
    NSDictionary *param = @{@"device_id": [[JDFacade facade].loginUser isMultiHomeHub] ? _selectHub.deviceId:[[JDFacade facade].loginUser getHomeHubID],
                            @"command_type":isStart? CMD_TYPE_UNPAIRING_START:CMD_TYPE_UNPAIRING_STOP,
                            @"cust_id": [[JDFacade facade].loginUser custId],
                            @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[CommandModel class]];
}


-(void)startLoading:(BOOL)isStart {
    _lblElapsedTime.hidden = !isStart;
    _imgLoading.hidden = !isStart;
    if (isStart) {
        _elapsedSeconds = kMaxTimeOut;
        NSLog(@"ElapsedSecond : %zd", _elapsedSeconds);
        _lblElapsedTime.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 ([_imgLoading.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;
                [_imgLoading.layer addAnimation:animation forKey:@"SpinAnimation"];
            }
        });
    }
    else {
        _elapsedSeconds = kMaxTimeOut;
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
        if ([_imgLoading.layer animationForKey:@"SpinAnimation"] != nil) {
            [_imgLoading.layer removeAnimationForKey:@"SpinAnimation"];
        }
        
    }

}

- (void)updateInclusionStatus {
    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        _lblElapsedTime.text = [NSString stringWithFormat:@"%zd", _elapsedSeconds];
        _elapsedSeconds--;
        
        if (_elapsedSeconds == 0) {
            [self didFailInclusion];
        }
    });
}

- (void)didFailExclusion {
    
    [self startLoading:NO];
    [self requestIncludeDevice:NO];
    
    ThingsAddFailViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddFailViewController" storyboardName:@"Things"];
    
    vc.addDevice = _addDevice;
    vc.selectHub = _selectHub;
//    vc.providesPresentationContextTransitionStyle = YES;
//    vc.definesPresentationContext = YES;
//    
//    [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
//    
//    UIViewController *pvc = self.presentingViewController;
//    [self dismissViewControllerAnimated:NO completion:^{//TODO : UI Confirm with Mr.Mo
//        [pvc presentViewController:vc animated:YES completion:nil];
//    }];
    [self showTransparencyModalView:vc];
}


- (void)didFailInclusion {
    [self startLoading:NO];
//    [self requestIncludeDevice:NO];
    
    ThingsAddFailViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddFailViewController" storyboardName:@"Things"];
    
    vc.addDevice = _addDevice;
    vc.selectHub = _selectHub;
//    vc.providesPresentationContextTransitionStyle = YES;
//    vc.definesPresentationContext = YES;
//    
//    [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
//    
//    UIViewController *pvc = self.presentingViewController;
//    [self dismissViewControllerAnimated:NO completion:^{//TODO : UI Confirm with Mr.Mo
//        [pvc presentViewController:vc animated:YES completion:nil];
//    }];
    [self showTransparencyModalView:vc];
}




#pragma mark - UI Events
- (IBAction)btnCancelTouched:(id)sender {
    
    [self startLoading:NO];
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
//        _maskView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [[JDFacade facade] dismissModalStack:NO completion:^{
            [[JDFacade facade] toast:@"취소되었습니다"];
        }];
    }];
}

#pragma mark - SocketService
- (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result
{
    if ([result.messageType isEqualToIgnoreCase:MSG_TYPE_DEVICE_COMMAND]) {
        CommandModel *response = (CommandModel *)message;
        if (result.isSuccess) {
            if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_PAIRING_START]) {
                _startCommand = response;
            }
            else if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_PAIRING_STOP]) {
                _stopCommand = response;
            }
            else if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_UNPAIRING_START]) {
                _startCommand = response;
            }
            else if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_UNPAIRING_STOP]) {
                _stopCommand = response;
            }
        }
        else {
            [self didFailInclusion];
        }
    }
}

- (void) socketDidFailWithError:(NSError *)error {
    [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
}

-(void) receiveSocketData:(NSNotification *)notification {
    SocketModel *result = [[SocketModel alloc] initWithDictionary:notification.object error:nil];
    CommandModel *response = [[CommandModel alloc] initWithDictionary:notification.object error:nil];
    
    //NSLog(@"Result : %@", result);
    //NSLog(@"Response : %@", response);
    
    if ([result.messageType isEqualToIgnoreCase:MSG_TYPE_DEVICE_COMMAND_RES]) {

        if (result.isSuccess) {
            if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_PAIRING_START]) {
                
                if ([response.commandId isEqualToString:_startCommand.commandId]) {
                    [self startLoading:YES];
                }
            }
            else if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_PAIRING_STOP]) {
                /*
                [self startLoading:NO];
                
                DeviceDetailModel *detailModel = [DeviceDetailModel new];
                detailModel.deviceId = _selectHub.deviceId;
                detailModel.nodeId = [notification.object objectForKey:@"node_id"];

                ThingsAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
                vc.deviceDetailModel = detailModel;
                vc.isDeleteMode = NO;
                 */
//                [self showTransparencyModalView:vc];
                
//                vc.providesPresentationContextTransitionStyle = YES;
//                vc.definesPresentationContext = YES;
//                
//                [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
//                
//                [self presentViewController:vc animated:YES completion:^{
//                    _maskView.alpha = 0.0f;
//                }];
//                [self showTransparencyModalView:vc];
            }
            if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_UNPAIRING_START]) {
                if ([response.commandId isEqualToString:_startCommand.commandId]) {
                    [self startLoading:YES];
                }
            }
            else if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_UNPAIRING_STOP]) {
                [self startLoading:NO];
                
//                ThingsAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
//                vc.isDeleteMode = NO;
//                
//                vc.providesPresentationContextTransitionStyle = YES;
//                vc.definesPresentationContext = YES;
//                
//                [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
//                
//                [self presentViewController:vc animated:YES completion:^{
//                    _maskView.alpha = 0.0f;
//                }];
                // TODO : 장치 삭제 완료 페이지로 이동
            }
        }
        else {
            [self didFailInclusion];
        }
    }
    else if ([result.messageType isEqualToIgnoreCase:MSG_TYPE_NODE_REGIST_RES]) {
//        [self requestIncludeDevice:NO];
        [self startLoading:NO];

        DeviceDetailModel *detailModel = [DeviceDetailModel new];
        detailModel.deviceId = _selectHub != nil ? _selectHub.deviceId : _addDevice.deviceId;
        detailModel.nodeId = [notification.object objectForKey:@"node_id"];
        detailModel.deviceId = [notification.object objectForKey:@"device_id"];

        ThingsAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
        vc.deviceDetailModel = detailModel;
        vc.isDeleteMode = NO;
        vc.addDevice = _addDevice;
        [self showTransparencyModalView:vc];
    }
}


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



@end
