//
//  CommandClassControlDetailView.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 "CustomRadioGroup.h"

#import "UIImageView+WebCache.h"

#import "CommandClassControlDetailView.h"
#import "CommandClassControlView.h"
#import "CustomImageView.h"

#define GRAPH_ANI_DUR 0.5f

#define kfControlDetailSwtchLeftPadding 45.0f
#define kfControlDetailSwtchRightPadding 28.0f

#define kfControlDetailDefaultWidth 320.0f
#define kfControlDetailDefaultHeight 285.0f

typedef void(^NodeCommandCompletionBlock)(id result);
typedef void(^NodeCommandFailureBlock)(id error);


@implementation CommandClassControlDetailView


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

    if (!controlView) {//상위 부모에서 가져옴.
        controlView = [CommandClassControlView viewForCommandClass:cmdClsType];
    }

    return controlView;
}


@end


@implementation CommandClassSwitchDetailView

- (void)setLayoutUI {
    [super setLayoutUI];
    
//    self.height = 347.0f;
    
//    NSString *stmp = @"켜기";
//    CGFloat width = [CommonUtil getSizeFromString:stmp font:_btnOff.titleLabel.font width:FLT_MAX].width;// + kfSwitchLabelPadding;
    
//    CGFloat eWidth = width + kfControlDetailSwtchLeftPadding + kfControlDetailSwtchRightPadding;
//    _constraintBtnSwitchWidth.constant = eWidth;
    
//    _btnOn.titleEdgeInsets = UIEdgeInsetsMake(0, 45, 0, 28);
//    _btnOff.titleEdgeInsets = UIEdgeInsetsMake(0, 45, 0, 28);
    
    _btnNode.enabled = _node.isDeviceOnline;
    _btnNode.selected = _btnNode.enabled && _isON;
    
    [self checkOffline];
}

- (IBAction)btnOnTouched:(id)sender {
    
    if (![self checkOnlineHub]) return;
    
    if (_isON) {
//        [[JDFacade facade] toast:@"이미 켜진 상태입니다"];
        return;
    }
//    [self requestNodeCommand:self.parameterForNodeCommand requestValue:_requestValueForOn completionHandler:nil failureHandler:nil];
//    [self requestNodeCommand:_requestValueForOn];
    [self requestNodeCommand:self.parameterForNodeCommand requestValue:[self requestValueForNodeCommand:_requestValueForOn]];
}

- (IBAction)btnOffTouched:(id)sender {

    if (![self checkOnlineHub]) return;
    
    if (!_isON) {
//        [[JDFacade facade] toast:@"이미 꺼진 상태입니다"];
        return;
    }
    
//    [self requestNodeCommand:self.parameterForNodeCommand requestValue:_requestValueForOff completionHandler:nil failureHandler:nil];
//    [self requestNodeCommand:_requestValueForOff];
    [self requestNodeCommand:self.parameterForNodeCommand requestValue:[self requestValueForNodeCommand:_requestValueForOff]];
}

- (BOOL)checkOnlineHub {
    
    if (![[JDFacade facade].loginUser onlineHomeHubFromSelectedHub:_selectHub]) {
        
        [[JDFacade facade] alert:@"허브가 오프라인 상태입니다. 허브 상태 확인 후 다시 시도해주세요." completionHander:nil];
        
        return NO;
    }
    
    return YES;
}

- (void)setSwitchBinary {
    
    _pcontainer.hidden = !_node.isRequesting;
    if (!_pcontainer.hidden) {
        [self startProgressAni];
    } else {
        [self stopProgressAni];
    }
    
//    _btnOn.enabled = _btnOff.enabled = _node.isDeviceOnline && [JDFacade facade].loginUser.isHomehubOnline;
    
    NSLog(@"_node.isDeviceOnline : %d", _node.isDeviceOnline);
    NSLog(@"_node.isDeviceOnline : %@", _selectHub);
    
    _btnOn.enabled = _node.isDeviceOnline ;
    
    _lblContentValueMsg.text = _node.contentValueMsg;
    
    _btnNode.userInteractionEnabled = NO;
    [_btnOn setImage:[_btnOn imageForState:_btnOn.state] forState:_btnOn.state];
//    [_btnOff setImage:[_btnOff imageForState:_btnOff.state] forState:_btnOff.state];
//    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateNormal] forState:UIControlStateNormal];
//    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateSelected] forState:UIControlStateSelected];
//    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateDisabled] forState:UIControlStateDisabled];
    _btnNode.selected = _isON;
    
    if (_isON) {//OFF
//        [_btnNode setImage:[UIImage imageNamed:@"img_things_detail_06_01_plug_state_on"] forState:UIControlStateNormal];
        [_btnOn setImage:[UIImage imageNamed:@"img_things_detail_06_99_btn_off"] forState:UIControlStateNormal];
        [_btnOn addTarget:self action:@selector(btnOffTouched:) forControlEvents:UIControlEventTouchUpInside];
        
    } else {//ON
//        [_btnNode setImage:[UIImage imageNamed:@"img_things_detail_06_01_plug_state_off"] forState:UIControlStateNormal];
        [_btnOn setImage:[UIImage imageNamed:@"img_things_detail_06_99_btn_on"] forState:UIControlStateNormal];
        [_btnOn addTarget:self action:@selector(btnOnTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)startProgressAni {
    
    //chagne button image
    [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
        _imgvProgress.transform = CGAffineTransformMakeRotation(M_PI);
    } completion:nil];
}

- (void)stopProgressAni {
    [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear  animations:^{
        _imgvProgress.transform = CGAffineTransformMakeRotation(0);
    } completion:^(BOOL finished) {
        _btnNode.enabled = _node.isDeviceOnline && [JDFacade facade].loginUser.isHomehubOnline;
        _btnNode.selected = _btnNode.enabled && _isON;
        
        [self checkOffline];
    }];
}

- (void)checkOffline {
    if (!_btnNode.enabled) {//online?
        self.lblContentValueMsg.text = @"OFFLINE";
        [self.lblContentValueMsg setColor:kUITextColor01 text:self.lblContentValueMsg.text];
    }
}

@end



@implementation CommandClassValveDetailView


- (void)setLayoutUI {
    [super setLayoutUI];
    
//    self.height = 347.0f;
    
//    NSString *stmp = @"잠그기";
//    CGFloat width = [CommonUtil getSizeFromString:stmp font:_btnClose.titleLabel.font width:FLT_MAX].width;// + kfSwitchLabelPadding;
    
//    CGFloat eWidth = width + kfControlDetailSwtchLeftPadding + kfControlDetailSwtchRightPadding;
//    _constraintBtnWidth.constant = eWidth;
    
//    _btnClose.titleEdgeInsets = UIEdgeInsetsMake(0, 45, 0, 28);
    
    [self checkOffline];
}

- (IBAction)btnCloseTouched:(id)sender {
    
    if (![[JDFacade facade].loginUser onlineHomeHubFromSelectedHub:_selectHub]) {
        
        [[JDFacade facade] alert:@"허브가 오프라인 상태입니다. 허브 상태 확인 후 다시 시도해주세요." completionHander:nil];
        
        return;
    }
    
    if (!_isOpened) {
        
        [[JDFacade facade] toast:@"이미 잠긴 상태입니다"];
        return;
    }
    //NSLog(@"Parameter : %@", self.parameterForNodeCommand);
//    [self requestNodeCommand:self.parameterForNodeCommand requestValue:_requestValueForClose completionHandler:nil failureHandler:nil];
//    [self requestNodeCommand:_requestValueForClose];
    [self requestNodeCommand:self.parameterForNodeCommand requestValue:[self requestValueForNodeCommand:_requestValueForClose]];
}

- (void)setSwitchBinary {
    
    _pcontainer.hidden = !_node.isRequesting;
    if (!_pcontainer.hidden) {
        [self startProgressAni];
    } else {
        [self stopProgressAni];
    }
    
    _btnClose.enabled = _node.isDeviceOnline && [JDFacade facade].loginUser.isHomehubOnline;
    
    _lblContentValueMsg.text = _node.contentValueMsg;
    
    if ([_node.contentValueMsg isEqualToString:@"잠김"]) {
        [self valveIsLock:YES];
    } else {
        [self valveIsLock:NO];
    }
    _btnNode.selected = _isOpened;
    [_btnClose setImage:[_btnClose imageForState:_btnClose.state] forState:_btnClose.state];
}

- (void)valveIsLock:(BOOL)lock{
    if (lock) {
        _lblContentValueMsg.textAlignment = NSTextAlignmentCenter;
        _btnClose.hidden = YES;
        [self.lblContentValueMsg setColor:kUITextColor01 text:self.lblContentValueMsg.text];
        _lblLeadingSpace.constant = 15.0f;
        _btnCloseWidth.constant = 0.0f;
    } else {
        _lblContentValueMsg.textAlignment = NSTextAlignmentLeft;
        _btnClose.hidden = NO;
        [self.lblContentValueMsg setColor:kUITextColor02 text:self.lblContentValueMsg.text];
        _lblLeadingSpace.constant = 23.0f;
        _btnCloseWidth.constant = 60.0f;
    }
}

- (void)startProgressAni {
    
    //chagne button image
    [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveLinear animations:^{
        _imgvProgress.transform = CGAffineTransformMakeRotation(M_PI);
    } completion:nil];
}

- (void)stopProgressAni {
    [UIView animateWithDuration:0.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear  animations:^{
        _imgvProgress.transform = CGAffineTransformMakeRotation(0);
    } completion:^(BOOL finished) {
        _btnNode.enabled = _node.isDeviceOnline && [JDFacade facade].loginUser.isHomehubOnline;
        _btnNode.selected = _btnNode.enabled && _isOpened;
        
        [self checkOffline];
    }];
}

- (void)checkOffline {
    if (!_btnNode.enabled) {//online?
        _btnClose.hidden = YES;
        _btnCloseWidth.constant = 0.0f;
        self.lblContentValueMsg.text = @"OFFLINE";
        self.lblContentValueMsg.textAlignment = NSTextAlignmentCenter;
        [self.lblContentValueMsg setColor:kUITextColor01 text:self.lblContentValueMsg.text];
    }
}

@end


#pragma mark - Sensors View

@implementation CommandClassSensorBinaryDetailView


- (void)setLayoutUI {
    [super setLayoutUI];
    
//    _lblNodeName.hidden = !_isMandatoryNode;
//    if (!_lblNodeName.hidden) {
//        _lblNodeName.text = _device.nodeName;
//    }
    
        _lblNodeName.hidden = [_node.contentLastDatetime isEmptyString];
        
//        _lblNodeName.text = [NSString stringWithFormat:@"마지막 동작 : %@", _node.deviceOnlineLastDatetime ];
        _lblNodeName.text = [NSString stringWithFormat:@"마지막 동작 : %@", [CommonUtil connectDataFromStr:_node.contentLastDatetime]];

    
    _btnNode.userInteractionEnabled = NO;
    
    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateNormal] forState:UIControlStateNormal];
    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateSelected] forState:UIControlStateSelected];
    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateDisabled] forState:UIControlStateDisabled];
    
    _btnNode.enabled = _node.isDeviceOnline && [JDFacade facade].loginUser.isHomehubOnline;
    _btnNode.selected = _btnNode.enabled && [_node.contentValue isEqualToString:@"TRUE"];
    
    if (_btnNode.enabled) {//online?
        [self.lblControl setColor:kUITextColor01 text:self.lblControl.text];

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

@end


@implementation CommandClassSensorMultiLevelDetailView


- (void)setLayoutUI {
    [super setLayoutUI];
    
    _btnNode.userInteractionEnabled = NO;
    
//    _lblNodeName.hidden = !_isMandatoryNode;
//    if (!_lblNodeName.hidden) {
//        _lblNodeName.text = _device.nodeName;
//    }
    
    
    _lblNodeName.hidden = [_node.deviceOnlineLastDatetime isEmptyString];
    _lblNodeName.text = [NSString stringWithFormat:@"마지막 동작 : %@", _node.deviceOnlineLastDatetime];

    
    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateNormal] forState:UIControlStateNormal];
    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateSelected] forState:UIControlStateSelected];
    [_btnNode setImage:[_node imageForMandataryForState:UIControlStateDisabled] forState:UIControlStateDisabled];
    
    _btnNode.enabled = _node.isDeviceOnline && [JDFacade facade].loginUser.isHomehubOnline;
    _btnNode.selected = _btnNode.enabled && [_node.contentValue isEqualToString:@"TRUE"];
    
    _lblCondition.hidden = !_node.isDeviceOnline || ![JDFacade facade].loginUser.isHomehubOnline;
    _lblCondition.text = [_node conditionForMandatary];
    
    if (_btnNode.enabled) {//online?
        [self.lblControl setColor:kUITextColor01 text:self.lblControl.text];
    } else {
        self.lblControl.text = @"OFFLINE";
        [self.lblControl setColor:kUITextColor01 text:self.lblControl.text];
    }
}

@end



