//
//  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"


@implementation CommandClassControlView


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

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

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

- (NSDictionary *)parameterForNodeCommand {
    NSDictionary *parameter = nil;
    if (_device) {
        parameter = @{@"device_id": _device.deviceId,
                      @"node_id": _device.nodeId};
    } else if (_node) {
        parameter = @{@"device_id": _node.deviceId,
                      @"node_id": _node.nodeId};
    }
    return parameter;
}

- (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 {

    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] sendAsyncPostRequestAPIPath:path parameters:param modelClass:[JDJSONModel class] completion:^(id responseObject) {
        if (completion) {
            completion(responseObject);
        }

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

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

- (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 prepareViewDidLoad];
        }
    }
}

@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;

    NSString *stmp = _device.cmdclsValueMsgLongest;
    CGFloat width = [CommonUtil getSizeFromString:stmp font:_btnSwitch.titleLabel.font width:FLT_MAX].width + kfSwitchLabelPadding;

    CGFloat eWidth = width + kfCommandClassSwitchLeftPadding + kfCommandClassSwitchRightPadding;
    _constraintBtnSwitchWidth.constant = eWidth;

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

    _btnSwitch.rectForCapBackground = CGRectMake(kfCommandClassSwitchLeftPadding, 0, kfCommandClassSwitchRightPadding, 0);

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

    [self setSwitchBinary];
    if (!_isON) {
        [_btnSwitch faceOffImage];
    }
}

- (IBAction)btnSwitchTouched:(id)sender {
    _device.cmdclsValue = _isON ? _requestValueForOn : _requestValueForOff;

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

    NSString *requestValue = _isON ? _requestValueForOff : _requestValueForOn;
    
    [CommandClassControlView requestNodeCommand:self.parameterForNodeCommand requestValue:requestValue completionHandler:^(id result) {
        _isON = !_isON;
        _device.contentValue = _isON ? _requestValueForOn : _requestValueForOff;
        [self toggleSwitch];

    } failureHandler:nil];
}

- (void)setSwitchBinary {
    if (_isON) {//OFF
        [_btnSwitch setTitle:_device.contentValueMsg forState:UIControlStateNormal];
        _btnSwitch.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        _btnSwitch.rectForCapBackground = CGRectMake(30, 0, 0, 40);
        
    } else {//ON
        [_btnSwitch setTitle:_device.contentValueMsg forState:UIControlStateNormal];
        _btnSwitch.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        _btnSwitch.rectForCapBackground = CGRectMake(40, 0, 0, 30);
    }
}

- (void)toggleSwitch {
    [self setSwitchBinary];
    [_btnSwitch faceOffImage];

    [self updateThingsViewContoller];
}

@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 : [self 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 = [self 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:@"%@%@", [self 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:@"%@%@", [self cmdclsValueForType:_device.dataTypeCode value:_currentValue], _device.unit ? _device.unit : ksEmptyString] forState:UIControlStateNormal];

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

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

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

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

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

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

@end


@implementation CommandClassThermostatModeView


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

    [self initControl];
}

- (void)initControl {

    [self setLayoutUI];
}

- (void)setLayoutUI {

    //todo contentValue 비교 추가,
    _modeArray = _device.cmdclsValueList;

    NSString *mode;
    NSUInteger highest = 0, i = 0;
    for (CmdClsValueModel *tmpCmdclsValue in _modeArray) {
        if (tmpCmdclsValue.cmdclsValueMsg.length > highest) {
            highest = tmpCmdclsValue.cmdclsValueMsg.length;
            mode = tmpCmdclsValue.cmdclsValueMsg;
        }

        if ([_device.contentValue isEqualToString:tmpCmdclsValue.cmdclsValue]) {
            _modeIndex = i;
        }
        i++;
    }

    CGFloat width = [CommonUtil getSizeFromString:mode 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;


    CmdClsValueModel *cmdclsValue = _modeArray[_modeIndex];
    
    if (!_isConditionMode) {//컨디션 모드가 아닐 경우,
        _device.cmdclsValue = cmdclsValue.cmdclsValue;
        [_btnLabel setTitle:_device.contentValueMsg forState:UIControlStateNormal];
        
    } else if (_isConditionTypeMode) {//컨디션 모드일 경우,
        _device.conditionTypeCode = cmdclsValue.cmdclsValue;
        [_btnLabel setTitle:_device.cmdclsValue forState:UIControlStateNormal];
    }
}


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

    _btnPrev.userInteractionEnabled = _enable;
    _btnNext.userInteractionEnabled = _enable;

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

        [_btnPrev setImage:[UIImage imageNamed:@"tp_01_img_control_unit_prev"] forState:UIControlStateNormal];
        [_btnNext setImage:[UIImage imageNamed:@"tp_01_img_control_unit_next"] forState:UIControlStateNormal];
    } else {
        [_btnLabel setTitleColor:kUITextColor03 forState:UIControlStateNormal];

        [_btnPrev setImage:[UIImage imageNamed:@"tp_01_img_control_unit_prev_disable"] forState:UIControlStateNormal];
        [_btnNext setImage:[UIImage imageNamed:@"tp_01_img_control_unit_next_disable"] forState:UIControlStateNormal];
    }
}


- (IBAction)btnNextTouchDown:(id)sender {

    if (!_pressTimer) {
        _pressTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(changeNextMode) userInfo:nil repeats:YES];
    }
}

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

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

    [self changeNextMode];
    [self requestCommand];
}

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

    [self changePrevMode];
    [self requestCommand];
}

- (void)changeNextMode {
    _modeIndex = _modeIndex + 1 == _modeArray.count ? 0 : _modeIndex + 1;

    CmdClsValueModel *cmdclsValue = _modeArray[_modeIndex];
    [_btnLabel setTitle:cmdclsValue.cmdclsValueMsg forState:UIControlStateNormal];

    if (!_isConditionTypeMode) {
        _device.cmdclsValue = cmdclsValue.cmdclsValue;
        [self updateThingsViewContoller];
    } else {//컨디션 모드일 경우,
        _device.conditionTypeCode = cmdclsValue.cmdclsValue;
    }
}

- (void)changePrevMode {
    _modeIndex = _modeIndex - 1 == -1 ? _modeArray.count - 1 : _modeIndex - 1;

    CmdClsValueModel *cmdclsValue = _modeArray[_modeIndex];
    [_btnLabel setTitle:cmdclsValue.cmdclsValueMsg forState:UIControlStateNormal];

    if (!_isConditionTypeMode) {
        _device.cmdclsValue = cmdclsValue.cmdclsValue;
        [self updateThingsViewContoller];
    } else {//컨디션 모드일 경우,
        _device.conditionTypeCode = cmdclsValue.cmdclsValue;
    }
}

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

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

@end

@implementation CommandClassThermostatFanModeView


@end

@implementation CommandClassThermostatSetPointView

- (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 : [self 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 = [self 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:@"%@%@", [self cmdclsValueForType:_device.dataTypeCode value:_currentValue], _device.unit ? _device.unit : ksEmptyString] forState:UIControlStateNormal];
}

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

    _btnDown.userInteractionEnabled = _enable;
    _btnUp.userInteractionEnabled = _enable;

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

        [_btnDown setImage:[UIImage imageNamed:@"tp_01_img_control_unit_down"] forState:UIControlStateNormal];
        [_btnUp setImage:[UIImage imageNamed:@"tp_01_img_control_unit_up"] forState:UIControlStateNormal];
    } else {
        [_btnLabel setTitleColor:kUITextColor03 forState:UIControlStateNormal];

        [_btnDown setImage:[UIImage imageNamed:@"tp_01_img_control_unit_down_disable"] forState:UIControlStateNormal];
        [_btnUp setImage:[UIImage imageNamed:@"tp_01_img_control_unit_up_disable"] forState:UIControlStateNormal];
    }
}

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

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

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

    [self addValue];
    [self requestCommand];
}

- (void)btnDownTouchUp:(id)sender {
    [_pressTimer invalidate];
    _pressTimer = nil;

    [self subtractValue];
    [self requestCommand];
}

- (void)addValue {
    _currentValue = _currentValue + _step > _maxValue ? _minValue : _currentValue + _step;
    [_btnLabel setTitle:[NSString stringWithFormat:@"%@%@", [self cmdclsValueForType:_device.dataTypeCode value:_currentValue], _device.unit ? _device.unit : ksEmptyString] forState:UIControlStateNormal];

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

- (void)subtractValue {
    _currentValue = _currentValue - _step < _minValue ? _maxValue : _currentValue - _step;
    [_btnLabel setTitle:[NSString stringWithFormat:@"%@%@", [self cmdclsValueForType:_device.dataTypeCode value:_currentValue], _device.unit ? _device.unit : ksEmptyString] forState:UIControlStateNormal];

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

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

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

@end



@implementation CommandClassLockView

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

    [self initControl];
}

- (void)initControl {

    _requestValueForOff = @"UNLOCKED";
    _requestValueForOn = @"LOCKED";

    [self setLayoutUI];
}

- (void)setLayoutUI {

    _device = _device ? _device : _node;
    CGFloat adjustRightPadding = kfCommandClassSwitchRightPadding;
    
    if ([_device.cmdclsTypeId isEqualToString:@"14002"]) {
        [_btnLock setImage:[UIImage imageNamed:@"tp_01_img_control_switch_lock_locking"] forState:UIControlStateNormal];
        [_btnLock setImage:nil forState:UIControlStateHighlighted];
        _constraintBtnLockWidth.constant = 32;
        _constraintBtnLabelWidth.constant = 159 - 32;
        [self layoutIfNeeded];
        
        adjustRightPadding = kfCommandClassLockRightPadding;
        
    } else if ([_device.cmdclsTypeId isEqualToString:@"14003"]) {
        [_btnLock setImage:[UIImage imageNamed:@"tp_01_img_control_switch_lock_unlocking"] forState:UIControlStateNormal];
        [_btnLock setImage:nil forState:UIControlStateHighlighted];        
        _constraintBtnLockWidth.constant = 32;
        _constraintBtnLabelWidth.constant = 159 - 32;    
        [self layoutIfNeeded];   
        
        adjustRightPadding = kfCommandClassLockRightPadding;
    }

    NSString *stmp = _device.cmdclsValueMsgLongest;
    CGFloat width = [CommonUtil getSizeFromString:stmp font:_btnLabel.titleLabel.font width:FLT_MAX].width + kfSwitchLabelPadding;


    CGFloat eWidth = width + kfCommandClassSwitchLeftPadding + adjustRightPadding;
    _constraintBtnLabelWidth.constant = eWidth;

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

    _isLocked = [_device.contentValue isEqualToString:_requestValueForOn];
    _device.cmdclsValue = _isLocked ? @"LOCK" : @"UNLOCK";
    [self setLock];
    
    if (!_isLocked) {
        [_btnLock faceOffImage];
    }
}

- (void)setLock {
    if (_isLocked) {//Unlocked
        [_btnLabel setTitle:_device.contentValueMsg forState:UIControlStateNormal];
//        _btnLabel.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
//        _btnLabel.rectForCapBackground = CGRectMake(40, 0, 0, 30);
        
    } else {//Locked
        [_btnLabel setTitle:_device.contentValueMsg forState:UIControlStateNormal];
//        _btnLabel.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
//        _btnLabel.rectForCapBackground = CGRectMake(30, 0, 0, 40);
    }
}

- (IBAction)btnLockTouched:(id)sender {
    _device.cmdclsValue = _isLocked ? @"LOCK" : @"UNLOCK";

    if (_isConditionMode) //룰, 씬일 경우, 제어를 하지 않음
        return;
    
    NSString *requestValue = _isLocked ? @"UNLOCK" : @"LOCK";
    [CommandClassControlView 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 toggleLock];

    } failureHandler:nil];
}

- (void)toggleLock {

    [self setLock];
    [_btnLock faceOffImage];
    [self updateThingsViewContoller];
}

@end

@implementation CommandClassAVPlaybackView

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

    [self initControl];
}

- (void)initControl {
    _requestValueForOff = @"PAUSED";
    _requestValueForOn = @"PLAYING";

    [self setLayoutUI];
}

- (void)setLayoutUI {

    _device = _device ? _device : _node;
    
    CGRect sr = self.frame;
    
    //FIXME : get image size
    UIImage *controlImage = [_btnPlayback imageForState:UIControlStateNormal];
    sr.size.width = controlImage.size.width;
    self.frame = sr;
    
    _isPlay = [_device.contentValue isEqualToString:_requestValueForOn];
    _device.cmdclsValue = _isPlay ? @"PLAY" : @"PAUSE";
    
    if (_isPlay) {
        [_btnPlayback faceOffImage];
    }
}


- (IBAction)btnPlaybackTouched:(id)sender {
    _device.cmdclsValue = _isPlay ? @"PLAY" : @"PAUSE";    
    
    if (_isConditionMode) //룰, 씬일 경우, 제어를 하지 않음
        return;

    NSString *requestValue = _isPlay ? @"PAUSE" : @"PLAY";
    [CommandClassControlView requestNodeCommand:self.parameterForNodeCommand requestValue:requestValue completionHandler:^(id result) {
        _isPlay = !_isPlay;
        _device.contentValue = _isPlay ? @"PLAYING" : @"PAUSED";
        [_btnPlayback faceOffImage];
        
        
        [self updateThingsViewContoller];

    } failureHandler:nil];
}
@end


#pragma mark - Sensors View

@implementation CommandClassSensorBinaryView

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

    [self initControl];
}

- (void)initControl {
    _lblControl.textColor = kUITextColor01;
    [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;

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

        if ([contentValue isEqualToString:@"TRUE"]) {
            [self.lblControl setColor:kUITextColor02 text:contentValue];
        }

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

        if ([contentValue isEqualToString:@"TRUE"]) {
            [self.lblControl setColor:kUITextColor02 text:contentValue];
        }
    }

    _constraintControlLabelWidth.constant = [CommonUtil getSizeFromString:self.lblControl.text font:self.lblControl.font width:kfControlMaxWidth].width;

    CGRect sr = self.frame;
    sr.size.width = _constraintControlLabelWidth.constant;
    self.frame = sr;
}

@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;

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

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

    }

    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 = kUITextColor01;
    [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


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

    [self initControl];
}

- (void)initControl {
    _lblCamera.textColor = kUITextColor01;
    [self setLayoutUI];
}

- (void)setLayoutUI {

    if (_device) {
        _lblCamera.text = [NSString stringWithFormat:@"%@", _device.nodeName];

    } else if (_node) {
        _lblCamera.text = [NSString stringWithFormat:@"%@", _node.nodeName];
    }

    _constraintControlLabelWidth.constant = [CommonUtil getSizeFromString:_lblCamera.text font:_lblCamera.font width:kfControlMaxWidth].width;

    CGRect sr = self.frame;
    sr.size.width = _constraintControlLabelWidth.constant;
    self.frame = sr;
}

@end


@implementation CommandClassSpeedControlView

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

    [self initControl];
}

- (void)initControl {

    [self setLayoutUI];
}

- (void)setLayoutUI {

    _modeArray = _device.cmdclsValueList;

    NSString *mode;
    NSUInteger highest = 0, i = 0;
    for (CmdClsValueModel *tmpCmdclsValue in _modeArray) {
        if (tmpCmdclsValue.cmdclsValueMsg.length > highest) {
            highest = tmpCmdclsValue.cmdclsValueMsg.length;
            mode = tmpCmdclsValue.cmdclsValueMsg;
        }

        if ([_device.contentValue isEqualToString:tmpCmdclsValue.cmdclsValue]) {
            _modeIndex = i;
        }
        i++;
    }

    CGFloat width = [CommonUtil getSizeFromString:mode 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;


    CmdClsValueModel *cmdclsValue = _modeArray[_modeIndex];
    
    if (!_isConditionMode) {//컨디션 모드가 아닐 경우,
        _device.cmdclsValue = cmdclsValue.cmdclsValue;
        [_btnLabel setTitle:_device.contentValueMsg forState:UIControlStateNormal];
        
    } else if (_isConditionTypeMode) {//컨디션 모드일 경우,
        _device.conditionTypeCode = cmdclsValue.cmdclsValue;
        [_btnLabel setTitle:_device.cmdclsValue forState:UIControlStateNormal];
    }
}


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

    _btnPrev.userInteractionEnabled = _enable;
    _btnNext.userInteractionEnabled = _enable;

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

        [_btnPrev setImage:[UIImage imageNamed:@"tp_01_img_control_unit_prev"] forState:UIControlStateNormal];
        [_btnNext setImage:[UIImage imageNamed:@"tp_01_img_control_unit_next"] forState:UIControlStateNormal];
    } else {
        [_btnLabel setTitleColor:kUITextColor03 forState:UIControlStateNormal];

        [_btnPrev setImage:[UIImage imageNamed:@"tp_01_img_control_unit_prev_disable"] forState:UIControlStateNormal];
        [_btnNext setImage:[UIImage imageNamed:@"tp_01_img_control_unit_next_disable"] forState:UIControlStateNormal];
    }
}


- (IBAction)btnNextTouchDown:(id)sender {

    if (!_pressTimer) {
        _pressTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(changeNextMode) userInfo:nil repeats:YES];
    }
}

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

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

    [self changeNextMode];
    [self requestCommand];
}

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

    [self changePrevMode];
    [self requestCommand];
}

- (void)changeNextMode {
    _modeIndex = _modeIndex + 1 == _modeArray.count ? 0 : _modeIndex + 1;

    CmdClsValueModel *cmdclsValue = _modeArray[_modeIndex];
    [_btnLabel setTitle:cmdclsValue.cmdclsValueMsg forState:UIControlStateNormal];

    if (!_isConditionTypeMode) {
        _device.cmdclsValue = cmdclsValue.cmdclsValue;
        [self updateThingsViewContoller];
    } else {//컨디션 모드일 경우,
        _device.conditionTypeCode = cmdclsValue.cmdclsValue;
    }
}

- (void)changePrevMode {
    _modeIndex = _modeIndex - 1 == -1 ? _modeArray.count - 1 : _modeIndex - 1;

    CmdClsValueModel *cmdclsValue = _modeArray[_modeIndex];
    [_btnLabel setTitle:cmdclsValue.cmdclsValueMsg forState:UIControlStateNormal];

    if (!_isConditionTypeMode) {
        _device.cmdclsValue = cmdclsValue.cmdclsValue;
        [self updateThingsViewContoller];
    } else {//컨디션 모드일 경우,
        _device.conditionTypeCode = cmdclsValue.cmdclsValue;
    }
}

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

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


@end
