//
//  CommandClassControlView.m
//  kneet
//
//  Created by Jason Lee on 3/16/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

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

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

#import "CommandClassControlView.h"
#import "ThingsDetailViewController.h"
#import "ThingsViewController.h"
#import "MainViewController.h"


#define MAX_CONTROL_REQUEST_TIME 10


@implementation CommandClassControlView


+ (CommandClassControlView *)viewForCommandClass:(CmdClsType)cmdClsType {
    CommandClassControlView *controlView = nil;
    for (UIView *view in [CommonUtil nibViews:@"CommandClassControlView"]) {
        if (view.tag == cmdClsType) {
            controlView = (CommandClassControlView *)view;
            
            controlView.width = kfControlDefaultWidth;
            controlView.height = kfControlDefaultHeight;
            
            break;
        }
    }
    return controlView;
}

- (void)setDevice:(DeviceModel *)device {
    _device = device;
}

- (void)setNode:(NodeModel *)node {
    _node = node;
}

- (void)setSelectHub:(DeviceModel *)selectHub {
    _selectHub = selectHub;
}


- (void)setLayoutUI {
    
}

- (void)updateLayout {
    
}
//todo : 로딩화면 띄우기
//예외처리 하기
- (NSDictionary *)parameterForNodeCommand {
    NSDictionary *parameter = nil;
    if (_device) {
        NSLog(@"Device : %@", _device);
        parameter = @{
                      @"device_id": _device.deviceId,
                      @"node_id": _device.nodeId};
    } else if (_node) {
        NSLog(@"Node : %@", _node);
        parameter = @{@"device_id": _node.deviceId,
                      @"node_id": _node.nodeId};
    }
    return parameter;
}

- (NSDictionary *)requestValueForNodeCommand:(NSString *)requestValue {
    NSDictionary *result = nil;
    if (_device) {
        result = @{_device.cmdclsId:requestValue};
    } else if (_node) {
        result = @{_node.cmdclsId:requestValue};
    }
    
    return result;
}

- (CGSize)sizeForIntrinsic {
    return CGSizeMake(kfControlMaxWidth, kfControlDefaultHeight);
}

- (CGSize)sizeForIntrinsicForItemCount:(NSInteger)count {
    return CGSizeMake(kfControlMaxWidth, kfControlDefaultHeight);
}

- (void)requestNodeCommand:(NSDictionary *)parameters requestValue:(NSString *)requestValue completionHandler:(NodeCommandCompletionBlock)completion failureHandler:(NodeCommandFailureBlock)failure {
    if (_device.isRequesting) {
        return;
    }

    _device.isRequesting = YES;
    
    [[[RACObserve(_device, contentValue) skip:1] take:1] subscribeNext:^(id x) {
        [self updateLayout];
    }];
    

    
    
    
    NSString *deviceId = parameters[@"device_id"];
    NSString *nodeId = parameters[@"node_id"];

    NSDictionary *param = @{@"request_value": requestValue};
    NSString *path = [NSString stringWithFormat:API_POST_NODE_COMMAND, deviceId, nodeId];

    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestPOST parameters:param modelClass:[DeviceModel class] showLoadingView:NO completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DeviceModel *result = (DeviceModel *)responseObject;
        if (result && result.commandId && ![result.commandId isEmptyString]) {
            
            _device.requestTime = result.requestTime;
            
            ThingsViewController *vc = [JDFacade facade].mainViewController.tvc;
            if (vc && [vc isKindOfClass:[ThingsViewController class]]) {
                [vc requestPollingCommandStatusOfDeviceInBackground:_device];
            }
        }
        
        if (completion) {
            completion(responseObject);
        }

    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];

        if (failure) {
            failure(error);
        }
    }];
}

- (void)requestNodeCommand:(NSDictionary *)parameters requestValue:(NSDictionary *)requestValue {
    if (_device.isRequesting) {
        return;
    }
    NSLog(@"Device : %@", _device);
    _device.isRequesting = YES;
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_NODE_COMMAND];
    
    NSDictionary *param = @{@"device_id": parameters[@"device_id"],
                            @"node_id":parameters[@"node_id"],
                            @"command_type":CMD_TYPE_CONTROL,
                            @"request_value":requestValue,
                            @"cust_id": [[JDFacade facade].loginUser custId],
                            @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
    
    [request setRequestMsg:param];
    
    [[SocketServiceHandler sharedManager] sendDataWithDelegate:request delegate:self];
    [self performSelector:@selector(chkRequstDeviceControlResult) withObject:nil afterDelay:MAX_CONTROL_REQUEST_TIME];
}

- (void)requestNodeCommand:(NSString *)requestValue {
    if (_device.isRequesting) {
        return;
    }
    NSLog(@"Device : %@", _device);
    _device.isRequesting = YES;
    
    [[[RACObserve(_device, contentValue) skip:1] take:1] subscribeNext:^(id x) {
        [self updateLayout];
    }];
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_NODE_COMMAND];
    
    NSDictionary *param = @{@"device_id": _device.deviceId,
                            @"node_id":_device.nodeId,
                            @"command_type":CMD_TYPE_CONTROL,
                            @"request_value":@{_device.cmdclsId:requestValue},
                            @"cust_id": [[JDFacade facade].loginUser custId],
                            @"ctrt_grp_id": [[JDFacade facade].loginUser ctrtGrpId]};
    
    
    [request setRequestMsg:param];
    
    [[SocketServiceHandler sharedManager] sendDataWithDelegate:request delegate:self];
    [self performSelector:@selector(chkRequstDeviceControlResult) withObject:nil afterDelay:MAX_CONTROL_REQUEST_TIME];
}

+ (NSString *)cmdclsValueForType:(NSString *)dataTypeCode value:(CGFloat)value {
    NSString *result = nil;
    if ([dataTypeCode isEqualToString:ksDataTypeCodeInteger]) {
        result = [NSString stringWithFormat:@"%zd", (NSInteger)value];

    } else if ([dataTypeCode isEqualToString:ksDataTypeCodeFloat]) {
        result = [NSString stringWithFormat:@"%.1f", value];
    } else {
        result = [NSString stringWithFormat:@"%zd", (NSInteger)value];
    }
    return result;
}

- (void)updateThingsViewContoller {
    if ([[JDFacade facade].currentViewController isKindOfClass:[ThingsDetailViewController class]]) {
        ThingsViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
        if (vc) {
            [vc prepareViewDidLoadRefreshPopup];
        }
    }
}


-(void) chkRequstDeviceControlResult {
    if (_device.isRequesting) {
        _device.isRequesting = NO;
        ThingsViewController *vc = [JDFacade facade].mainViewController.tvc;
        if (vc && [vc isKindOfClass:[ThingsViewController class]]) {
            [vc requestDeviceControl];
        }
    }
}


- (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result
{

    if (result.isSuccess) {
        ThingsViewController *vc = [JDFacade facade].mainViewController.tvc;
        if (vc && [vc isKindOfClass:[ThingsViewController class]]) {
            [vc requestDeviceControl];
        }
    } else {
        _device.isRequesting = NO;
    }
}

@end


@implementation CommandClassSwitchView

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (!newSuperview)
        return;

    [self initControl];
}

- (void)initControl {

    _requestValueForOff = @"OFF";
    _requestValueForOn = @"ON";

    [self setLayoutUI];
}

- (void)setLayoutUI {
    
    _device = _device ? _device : _node;

    _isON = [_device.contentValue isEqualToString:_requestValueForOn];
    _device.cmdclsValue = _isON ? _requestValueForOff : _requestValueForOn;
    _lblContentValueMsg.text = _device.contentValueMsg;

    _btnSwitch.hidden = self.isReOrderMode;
    
    [self setSwitchBinary];
}

- (IBAction)btnSwitchTouched:(id)sender {

    
    NSLog(@"_device : %@", _device) ;
    
    if (![[JDFacade facade].loginUser onlineHomeHubFromSelectedHub:_selectHub]) {
        
        [[JDFacade facade] alert:@"허브가 오프라인 상태입니다. 허브 상태 확인 후 다시 시도해주세요." completionHander:nil];
        
        return;
    }
    
    
    
    NSString *requestValue = _isON ? _requestValueForOff : _requestValueForOn;
    _device.cmdclsValue = requestValue;
    
//    [self requestNodeCommand:self.parameterForNodeCommand requestValue:requestValue completionHandler:^(id result) {
//
////        _device.contentValue = requestValue;
////        _isON = !_isON;
////        _device.contentValue = _isON ? _requestValueForOn : _requestValueForOff;
////        [self toggleSwitch];
//
//    } failureHandler:nil];
//    [self requestNodeCommand:requestValue];
    [self requestNodeCommand:self.parameterForNodeCommand requestValue:[self requestValueForNodeCommand:requestValue]];
}

- (void)setSwitchBinary {
    
    _lblContentValueMsg.text = _device.contentValueMsg;
//    [_btnSwitch setTitle:_device.cmdclsValueMsg forState:UIControlStateNormal];
    
    if (_isON) {//OFF
        [_btnSwitch setImage:[UIImage imageNamed:@"img_things_list_btn_onoff_on"] forState:UIControlStateNormal];
        [self.lblContentValueMsg setColor:kUITextColor02 text:self.lblContentValueMsg.text];
        
    } else {//ON
        [_btnSwitch setImage:[UIImage imageNamed:@"img_things_list_btn_onoff_off"] forState:UIControlStateNormal];
    }
}

- (void)toggleSwitch {
    [self setSwitchBinary];

    [self updateThingsViewContoller];
}

- (void)updateLayout {
    _isON = !_isON;
    [self setSwitchBinary];
}

@end

@implementation CommandClassSwitchMultiLevelView

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (!newSuperview)
        return;

    [self initControl];
}

- (void)initControl {

    [self setLayoutUI];
}

- (void)setLayoutUI {

    _device = _device ? _device : _node;

    _device.cmdclsValue = _device.cmdclsValue ? _device.cmdclsValue : [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:[_device.controlMaxValue floatValue]/ 2];

    _currentValue = !_isConditionMode ? [_device.contentValue floatValue] : [_device.cmdclsValue floatValue];
    _minValue = [_device.controlMinValue floatValue];
    _maxValue = [_device.controlMaxValue floatValue];
    _step = [_device.controlStep floatValue];

    NSString *sMax = [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:_maxValue];
    CGFloat width  = [CommonUtil getSizeFromString:sMax font:_btnLabel.titleLabel.font width:FLT_MAX].width + kfSwitchLabelPadding;

    CGFloat eWidth = width + kfCommandClassSwitchLeftPadding + kfCommandClassSwitchRightPadding;
    eWidth = eWidth < kfControlDefaultWidth ? kfControlDefaultWidth : eWidth;

    _constraintBtnLabelWidth.constant = eWidth;

    CGRect sr = self.frame;
    sr.size.width = eWidth;
    self.frame = sr;

    [_btnLabel setTitle:[NSString stringWithFormat:@"%@%@", [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:_currentValue], _device.unit ? _device.unit : ksEmptyString] forState:UIControlStateNormal];
}

- (void)setEnable:(BOOL)enable {
    _enable = enable;

    _btnMinus.userInteractionEnabled = _enable;
    _btnPlus.userInteractionEnabled = _enable;

    if (_enable) {
        [_btnLabel setTitleColor:kUITextColor02 forState:UIControlStateNormal];

        [_btnMinus setImage:[UIImage imageNamed:@"tp_01_img_control_unit_minus"] forState:UIControlStateNormal];
        [_btnPlus setImage:[UIImage imageNamed:@"tp_01_img_control_unit_plus"] forState:UIControlStateNormal];
    } else {
        [_btnLabel setTitleColor:kUITextColor03 forState:UIControlStateNormal];

        [_btnMinus setImage:[UIImage imageNamed:@"tp_01_img_control_unit_minus_disable"] forState:UIControlStateNormal];
        [_btnPlus setImage:[UIImage imageNamed:@"tp_01_img_control_unit_plus_disable"] forState:UIControlStateNormal];
    }
}

- (IBAction)btnPlusTouchDown:(id)sender {
    if (!_pressTimer) {
        _pressTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(addValue) userInfo:nil repeats:YES];
    }
}

- (void)btnMinusTouchDown:(id)sender {
    if (!_pressTimer) {
        _pressTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(subtractValue) userInfo:nil repeats:YES];
    }
}

- (IBAction)btnPlusTouchUp:(id)sender {
    [_pressTimer invalidate];
    _pressTimer = nil;

    [self addValue];
    [self requestCommand];
}

- (IBAction)btnMinusTouchUp:(id)sender {
    [_pressTimer invalidate];
    _pressTimer = nil;

    [self subtractValue];
    [self requestCommand];
}

- (void)addValue {

    _currentValue = _currentValue + _step > _maxValue ? _minValue : _currentValue + _step;

    [_btnLabel setTitle:[NSString stringWithFormat:@"%@%@", [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:_currentValue], _device.unit ? _device.unit : ksEmptyString] forState:UIControlStateNormal];

    if (_device) {
        _device.cmdclsValue = [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:_currentValue];
        [self updateThingsViewContoller];
    }
}

- (void)subtractValue {
    _currentValue = _currentValue - _step < _minValue ? _maxValue : _currentValue - _step;

    [_btnLabel setTitle:[NSString stringWithFormat:@"%@%@", [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:_currentValue], _device.unit ? _device.unit : ksEmptyString] forState:UIControlStateNormal];

    if (_device) {
        _device.cmdclsValue = [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:_currentValue];
        [self updateThingsViewContoller];
    }
}

- (void)requestCommand {
    if (_isConditionMode) //룰, 씬일 경우, 제어를 하지 않음
        return;

    NSString *requestValue = _device.cmdclsValue;
//    [self requestNodeCommand:self.parameterForNodeCommand requestValue:requestValue completionHandler:^(id result) {
//        _device.contentValue = [CommandClassControlView cmdclsValueForType:_device.dataTypeCode value:_currentValue];
//    } failureHandler:nil];
    
//    [self requestNodeCommand:requestValue];
    [self requestNodeCommand:self.parameterForNodeCommand requestValue:[self requestValueForNodeCommand:requestValue]];
}

@end


@implementation CommandClassValveView

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (!newSuperview)
        return;

    [self initControl];
}

- (void)initControl {

    _requestValueForOpen = @"OPEN";
    _requestValueForClose = @"CLOSE";

    [self setLayoutUI];
}

- (void)setLayoutUI {

    _device = _device ? _device : _node;
    _lblContentValueMsg.text = _device.contentValueMsg;

    
    _isOpened = [_device.contentValue isEqualToString:_requestValueForOpen];
    _device.cmdclsValue = _isOpened ? _requestValueForClose : _requestValueForOpen;

    if ([_device.contentValue isEqualToString:_requestValueForOpen]) {
        [self.lblContentValueMsg setColor:kUITextColor02 text:self.lblContentValueMsg.text];
    }
    
    _btnOpen.hidden = self.isReOrderMode;
    
    [self setSwitchBinary];
}


- (void)setSwitchBinary {

    if (_isOpened) {//Unlocked
//        [_btnOpen setImage:[UIImage imageNamed:@"img_things_list_btn_lockunlock_unlock"] forState:UIControlStateNormal];
            [_btnOpen setImage:[UIImage imageNamed:@"img_things_list_btn_onoff_on"] forState:UIControlStateNormal];
        
    } else {//Locked
//        [_btnOpen setImage:[UIImage imageNamed:@"img_things_list_btn_lockunlock_lock"] forState:UIControlStateNormal];
            [_btnOpen setImage:[UIImage imageNamed:@"img_things_list_btn_onoff_off"] forState:UIControlStateNormal];
    }
}


- (IBAction)btnOpenTouched:(id)sender {
    
    NSLog(@"btnOpenTouched");
    
    NSLog(@"_device : %@", _device) ;
    NSLog(@"_node : %@", _node) ;
    
    if (![[JDFacade facade].loginUser onlineHomeHubFromSelectedHub:_selectHub]) {
        
        [[JDFacade facade] alert:@"허브가 오프라인 상태입니다. 허브 상태 확인 후 다시 시도해주세요." completionHander:nil];
        
        return;
    }
    
    NSString *requestValue = _isOpened ? @"CLOSE" : @"OPEN";
    if ([_device.cmdclsTypeId isEqualToString:@"36002"]) {
        requestValue = @"CLOSE";
        
        if (!_isOpened) {
            [[JDFacade facade] toast:@"이미 잠긴 상태입니다"];
            return;
        }
    }
    
    _device.cmdclsValue = requestValue;
    
//    [self requestNodeCommand:self.parameterForNodeCommand requestValue:requestValue completionHandler:^(id result) {
//        
////        if ([_device.cmdclsTypeId isEqualToString:@"14001"]) {//Lock.Default일 경우에만 컨트롤을 토글시킴.
////            _isLocked = !_isLocked;
////            _device.contentValue = _isLocked ? @"LOCKED" : @"UNLOCKED";
////        } else if ([_device.cmdclsTypeId isEqualToString:@"14002"]) {
////            _isLocked = YES;
////            _device.contentValue = @"LOCKED";
////        } else if ([_device.cmdclsTypeId isEqualToString:@"14003"]) {
////            _isLocked = NO;
////            _device.contentValue = @"UNLOCKED";
////        }
//        
//        [self toggleOpenButton];
//
//    } failureHandler:nil];
//    [self requestNodeCommand:requestValue];
    [self requestNodeCommand:self.parameterForNodeCommand requestValue:[self requestValueForNodeCommand:requestValue]];
}

- (void)toggleOpenButton {

    [self setSwitchBinary];
//    [_btnSwitch faceOffImage];
    [self updateThingsViewContoller];
}


@end



#pragma mark - Sensors View

@implementation CommandClassSensorBinaryView

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (!newSuperview)
        return;

    [self initControl];
}

- (void)initControl {
    
    [self setLayoutUI];
}

- (void)setLayoutUI {

    _device = _device ? _device : _node;
    NSString *contentValue = _device.contentValueMsg;

    NSString *unit = _device.unit && ![_device.unit isEmptyString] ? _device.unit : ksEmptyString;
    unit = [contentValue isEqualToString:@"-"] ? ksEmptyString : unit;

    self.lblControl.text = [NSString stringWithFormat:@"%@ %@", contentValue, unit];
    if ([_device.contentValue isEqualToString:@"TRUE"]) {
        [self.lblControl setColor:kUITextColor02 text:self.lblControl.text];
    }
}

@end


@implementation CommandClassSensorMultiLevelView


- (void)setLayoutUI {

    _device = _device ? _device : _node;
    NSString *contentValue = (!_device.contentValue || [_device.contentValue isEmptyString] ||[_device.contentValue isEqualToString:@"none"]) ? @"-" : _device.contentValue;
    NSString *unit = _device.unit && ![_device.unit isEmptyString] ? _device.unit : ksEmptyString;
    unit = [contentValue isEqualToString:@"-"] ? ksEmptyString : unit;

    self.lblControl.text = [NSString stringWithFormat:@"%@%@", contentValue, unit];

//    if (self.constraintControlLabelWidth) {
//        self.constraintControlLabelWidth.constant = [CommonUtil getSizeFromString:self.lblControl.text font:self.lblControl.font width:kfControlMaxWidth].width;
//        
//        CGRect sr = self.frame;
//        sr.size.width = self.constraintControlLabelWidth.constant;
//        self.frame = sr;
//    }
}


@end


@implementation CommandClassMeterCurrentView

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (!newSuperview)
        return;

    [self initControl];
}

- (void)initControl {
    _lblMeter.textColor = kUITextColor02;
    [self setLayoutUI];
}

- (void)setLayoutUI {

    _device = _device ? _device : _node;
    NSString *contentValue = (!_device.contentValue || [_device.contentValue isEmptyString] ||[_device.contentValue isEqualToString:@"none"]) ? @"-" : _device.contentValue;
    NSString *unit = _device.unit && ![_device.unit isEmptyString] ? _device.unit : ksEmptyString;
    unit = [contentValue isEqualToString:@"-"] ? ksEmptyString : unit;

    if (_node) {//디바이스 상세일 경우,
        self.lblMeter.text = [NSString stringWithFormat:@"%@ %@", contentValue, unit];
        self.lblMeter.font = [UIFont systemFontOfSize:kUIFontSize07];

    } else if (_device) {
        self.lblMeter.text = [NSString stringWithFormat:@"%@ : %@ %@", _device.nodeName, contentValue, unit];
        [self.lblMeter setColor:kUITextColor02 text:contentValue];

    }

//    self.constraintControlLabelWidth.constant = [CommonUtil getSizeFromString:self.lblMeter.text font:self.lblMeter.font width:kfControlMaxWidth].width;
//
//    CGRect sr = self.frame;
//    sr.size.width = self.constraintControlLabelWidth.constant;
//    self.frame = sr;
}

@end

@implementation CommandClassMeterTotalView



@end


