//
//  ThingsDelPlugViewController.m
//  OneCable
//
//  Created by nComz on 2017. 3. 21..
//  Copyright © 2017년 ntels. All rights reserved.
//

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

#import "ThingsForcedDelCompleteViewController.h"

// 오프라인 장치 강제 삭제
@interface ThingsForcedDelViewController () {
    NSTimer *_timer;
    NSInteger _elapsedSeconds;
    
    CommandModel *_startCommand;
    CommandModel *_stopCommand;
}

@end

@implementation ThingsForcedDelViewController

// 가스 밸브 타이틀 : 가스 밸브 삭제
// 가스 밸브 삭제 코멘트 : 동일
// 가스 밸브 이미지명 : img_things_product_addimg_01_smartgasvalve

// 도어센서 타이틀 : 도어 센서 삭제
// 도어센서 삭제 코멘트 : 동일
// 도어센서 이미지 명 : img_things_product_addimg_02_mutisensor_door

// 스마트플러그 타이틀 : 스마트 플러그 삭제
// 스마트플러그 삭제 코멘트 : 동일
// 스마트플러그 이미지 명 : img_things_product_addimg_03_smartplug

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self initUI];
    [self prepareViewDidLoad];
}

- (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)initUI {
//    [self initTableViewAsDefaultStyle:_tableView];
    [self startLoading:NO];
}

- (void)prepareViewDidLoad {
//    [self startLoading:NO];
    _imgThings.image = [_delDevice imgaeForAddDel];
    _lblManufacturer.text = [_delDevice manufacturerName];
    _lblTitle.text = [NSString stringWithFormat:@"%@ 삭제", _delDevice.prdName];
}

#pragma mark - Main Logic
- (void)requestForceDelDevice:(BOOL)isStart {
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_DEVICE_COMMAND];
    
    NSDictionary *param = @{@"device_id": _delDevice.deviceId,
                            @"command_type":isStart? CMD_TYPE_FORCE_NODE_DEL:CMD_TYPE_PAIRING_STOP,
                            @"request_value":@{@"failed_node": _delDevice.nodeId},
                            @"cust_id": [[JDFacade facade].loginUser custId],
                            @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
    [request setRequestMsg:param];
    NSLog(@"Request : %@", request);
    [self sendDataToSocket:request modelClass:[CommandModel class]];
}

-(void)startLoading:(BOOL)isStart {
    _imgLoading.hidden = !isStart;
    if (isStart) {
        _elapsedSeconds = kMaxTimeOut;
        NSLog(@"ElapsedSecond : %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) {
//        
//        _elapsedSeconds--;
//        
//        if (_elapsedSeconds == 0) {
//            [self finishDeviceDel:NO];
//        }
//    });
}

- (void)finishDeviceDel:(BOOL)isSuccess {
    [self startLoading:NO];
    ThingsForcedDelCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsForcedDelCompleteViewController" storyboardName:@"Things"];
    vc.delDevice = _delDevice;
    vc.isSuccess = isSuccess;
//    vc.addableDevice = _addableDevice;
    
    [self showTransparencyModalView:vc];
}

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

- (IBAction)btnStartTouched:(id)sender {
    
    if (![[JDFacade facade].loginUser onlineHomeHubFromSelectedHub:_delDevice]) {
        
        [[JDFacade facade] alert:@"허브가 오프라인 상태입니다. 허브 상태 확인 후 다시 시도해주세요." completionHander:^{
            
            [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        return;
    }
    
    
    [self requestForceDelDevice:YES];
}

#pragma mark - SocketService
- (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result
{
//    NSLog(@"Result Info : %@", result);
//    NSLog(@"Result Info : %@", message);
//    
    //    if (result.messageType) {
    //        <#statements#>
    //    }
//    NSLog(@"Message Type : %@", result.messageType);
    if ([result.messageType isEqualToIgnoreCase:MSG_TYPE_DEVICE_COMMAND]) {
        CommandModel *response = (CommandModel *)message;
        if (result.isSuccess) {
            if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_FORCE_NODE_DEL]) {
                [self startLoading:YES];
                _startCommand = response;
            }
        }
        else {
            [self finishDeviceDel:NO];
        }
    }
}

- (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]) {
        //NSLog(@"Response : %@", response);
        if (result.isSuccess) {
            if ([response.commandType isEqualToIgnoreCase:CMD_TYPE_FORCE_NODE_DEL]) {
//                if ([response.commandId isEqualToString:_startCommand.commandId]) {
//                    [self startLoading:YES];
//                }
                if (![response.commandStatus isEqualToIgnoreCase:@"SUCCESS"]) {
                    [self finishDeviceDel:NO];
                }
            }
            
        }
        else {
            [self finishDeviceDel:NO];
        }
    }
    else if ([result.messageType isEqualToIgnoreCase:MSG_TYPE_NODE_DELETE_RES]) {
//        [self requestIncludeDevice:NO];
        SoKNodeModel *result = [[SoKNodeModel alloc] initWithDictionary:notification.object error:nil];
//        if ([result.nodeId]) {
//            <#statements#>
//        }
        
        [self finishDeviceDel:[result.delYn isEqualToIgnoreCase:@"Y"]];
    }
}


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



@end
