//
//  WallpadSubDevicePopupView.m
//  kneet
//
//  Created by Jason Lee on 7/21/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "RequestHandler.h"
#import "DeviceModel.h"

#import "CustomLabel.h"
#import "CustomTextField.h"

#import "DeviceModel.h"
#import "WallpadSubDevicePopupView.h"
#import "ValidateUtil.h"
#import "LDProgressView.h"

#define kfWallpadAddSubDeviceTimeMax   60.0f

@interface WallpadSubDevicePopupView () <CustomTextFieldDelegate> {
    NSTimer *_progressTimer;
    CGFloat _sec;
    NSString *_commandId;
    BOOL _isRequesting;
}

@end

@implementation WallpadSubDevicePopupView

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"WallpadSubDevicePopupView"]) {
        if ([view isKindOfClass:[WallpadSubDevicePopupView class]]) {
            self = (WallpadSubDevicePopupView *)view;
            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            self.lblTitle.text = NSLocalizedString(@"장치 검색", @"장치 검색");


            _progressView.color = kUILineColor;
            _progressView.flat = @YES;
            _progressView.animate = @YES;
            _progressView.showText = @NO;
            _progressView.showStroke = @NO;
            _progressView.progressInset = @5;
            _progressView.showBackground = @NO;
            _progressView.outerStrokeWidth = @3;
            _progressView.type = LDProgressSolid;
            
            [self.btnConfirm setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

- (void)didMoveToSuperview {

}

- (void)setWallpadId:(NSString *)wallpadId {
    _wallpadId = wallpadId;
    
    //타이머를 시작함.
//    _sec = 0;
//    _progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(progressInvalidate) userInfo:nil repeats:YES];
    [self requestAddWallPadSubDevice];
}

- (void)requestAddWallPadSubDevice {
    //parameters
    NSDictionary *parameter = @{@"request_value": @"ADD",
                                @"request_value_type": ksEmptyString,
                                @"command_type": ksEmptyString};
    
    NSString *path = [NSString stringWithFormat:API_POST_DEVICE_INCLUSION, _wallpadId];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[DeviceModel class] showLoadingView:@(NO) completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DeviceModel *commandOfDevice = (DeviceModel *)responseObject;
        if (commandOfDevice) {//API 성공,
            _commandId = commandOfDevice.commandId;
            
            //타이머를 시작함.
            _sec = 0;
            _progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(progressInvalidate) userInfo:nil repeats:YES];
        }
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)progressInvalidate {
    _sec++;
    
    CGFloat progress = _sec / kfWallpadAddSubDeviceTimeMax;
    _progressView.progress = progress;
    if (_sec >= kfWallpadAddSubDeviceTimeMax && !_isRequesting) {
        [_progressTimer invalidate];
        
        //do next stub.
        [self btnConfirmTouched:nil];
        [[JDFacade facade] alert:NSLocalizedString(@"새로운 장치가\n발견되지 않았습니다", @"새로운 장치가\n발견되지 않았습니다")];
        return;
    }
    
    if ((int)_sec % 3 == 1 && !_isRequesting) {//serial queue,
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
            _isRequesting = YES;
            
            //parameters
            NSDictionary *parameter = @{@"command_id": _commandId};
            
            NSString *path = [NSString stringWithFormat:API_GET_DEVICE_COMMAND, _wallpadId];
            DeviceModel *commandOfDevice = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:parameter
                                                                                    modelClass:[DeviceModel class] showLoadingView:@(NO)];
            if (commandOfDevice) {
                if ([commandOfDevice.status isEqualToString:@"INC"]) {//추가
                    
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        _foundedDevice = commandOfDevice;
                        
                        [_progressTimer invalidate];
                        [self btnConfirmTouched:nil];                        
                    });
                    
                } else if ([commandOfDevice.status isEqualToString:@"EXC"]) {//삭제
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        _foundedDevice = commandOfDevice;
                        
                        [_progressTimer invalidate];
                        [self btnConfirmTouched:nil];                        
                    });
                    
                } else if ([commandOfDevice.status isEqualToString:@"WAT"]) {//대기
                    //do nothing
                }
            }
            
            _isRequesting = NO;
        });
    }
}

#pragma mark - Main Logic

- (void)actionForDiscoveredDevice:(DeviceModel *)device {
    
}

#pragma mark - UI Events
- (void)btnConfirmTouched:(id)sender {
    
    [_progressTimer invalidate];
    _progressTimer = nil;
    
    [super btnConfirmTouched:sender];
}

@end
