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

#import "RequestHandler.h"
#import "ItemModel.h"
#import "DeviceModel.h"

#import "CustomLabel.h"
#import "CustomRadioGroup.h"
#import "SelectButton.h"

#import "ValidateUtil.h"

#import "CommandClassControlView.h"
#import "ExternHeatPopupView.h"

@interface ExternHeatPopupView () {
    CustomRadioGroup *_rgroup;
    DeviceModel *_device;
    NSArray<CommonCode> *_locations;
    ItemSubModel *_subCondition;
    CommandClassThermostatSetPointView *_controlView;
}

@end

@implementation ExternHeatPopupView
@synthesize condition = _condition;

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"ExternHeatPopupView"]) {
        if ([view isKindOfClass:[ExternHeatPopupView class]]) {
            self = (ExternHeatPopupView *)view;

            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            self.lblTitle.text = NSLocalizedString(@"지역온도가 이 상태일 때만", @"지역온도가 이 상태일 때만");

            _rgroup = [[CustomRadioGroup alloc] init];
            [_rgroup addRadioButton:_rdoOver];
            [_rgroup addRadioButton:_rdoUnder];


            _device = [[DeviceModel alloc] init];
            _device.controlMinValue = @"-100";
            _device.controlMaxValue = @"200";
            _device.controlStep = @"1";
            _device.cmdclsValue = @"25";
            _device.dataTypeCode = @"01";

            _controlView = (CommandClassThermostatSetPointView *)[CommandClassControlView viewForCommandClass:CmdClsTypeThermostatSetPoint];
            _controlView.device = _device;
            _controlView.isConditionMode = YES;

            [_controlContainerView addSubview:_controlView];

            [_controlView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_controlContainerView.mas_top);
                make.left.equalTo(_controlContainerView.mas_left);
                make.center.equalTo(_controlContainerView);
            }];
            
            //Localization
            _lblHeat.text = NSLocalizedString(@"온도", @"온도");
            _lblUnit.text = NSLocalizedString(@"℃", @"℃");
            
            [_rdoOver setTitle:NSLocalizedString(@"이상", @"이상") forState:UIControlStateNormal];
            [_rdoUnder setTitle:NSLocalizedString(@"이하", @"이하") forState:UIControlStateNormal];
            
            _lblDesc.text = NSLocalizedString(@"바깥온도 설정은 Yahoo웨더의\n온도값을 기준으로 합니다", @"바깥온도 설정은 Yahoo웨더의\n온도값을 기준으로 합니다");
            
            [self.btnConfirm setTitle:NSLocalizedString(@"선택", @"선택") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

- (void)didMoveToSuperview {

}

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

    if (!_locations) {
        [self requestLocationCode];
    }
}

- (void)requestLocationCode {

    NSString *path = [NSString stringWithFormat:API_GET_LOCATION_CODES];

    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[CommonCodeList class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        CommonCodeList *result = (CommonCodeList *) responseObject;

        if (result) {//API 성공 ,
            _locations = result.list;
            [self setLocations];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


- (void)setLocations {
    NSArray *keys = [_locations valueForKeyPath:@"commonCode"];
    NSArray *values = [_locations valueForKeyPath:@"commonCodeName"];

    NSDictionary *dic = [NSDictionary dictionaryWithObjects:values forKeys:keys];

    _btnLocation.dataDict = [[SortDictionary alloc] initWithDictionary:dic];

    if (_subCondition.sourceId) {
        [_btnLocation setSelectedValue:_subCondition.sourceId];
    }
}


- (void)setCondition:(ItemModel *)condition {

    _condition = condition;

    if (!_condition) {
        _condition = [[ItemModel alloc] init];
        _condition.itemName = NSLocalizedString(@"지역온도", @"지역온도");
        _condition.itemSubTypeCode = ksConditionSubTypeCodeExternHeat;
    }

    if (_condition.subItems && _condition.subItems.count) {
        _subCondition = _condition.subItems[0];
    } else {
        _subCondition = [[ItemSubModel alloc] init];

        _condition.subItems = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithObjects:_subCondition, nil];
    }

    if (_subCondition.cmdclsValue) {
        _controlView.device.cmdclsValue = _subCondition.cmdclsValue;
        [_controlView.btnLabel setTitle:_subCondition.cmdclsValue forState:UIControlStateNormal];
    }
}

- (ItemModel *)condition {
    //1.Validate
    if (![self validateCondition]) {
        return nil;
    }

    _subCondition.sourceId = [self externLocation];
    _subCondition.conditionTypeCode = [self externCondition];
    _subCondition.cmdclsValue = _device.cmdclsValue;
    _subCondition.externHeat = [NSString stringWithFormat:@"%@ %@℃ %@", _btnLocation.selectedTitle, _subCondition.cmdclsValue, self.isOver ? NSLocalizedString(@"이상", @"이상"): NSLocalizedString(@"이하", @"이하")];

    return _condition;
}

- (NSString *)externHeat {
    return _subCondition.externHeat;
}

- (NSString *)externLocation {
    return _btnLocation.selectedValue;
}

- (NSString *)externCondition {
    return self.isOver ? @"05" : @"03";
}

- (BOOL)isOver {
    return _rdoOver.checked;
}

- (BOOL)validateCondition {

    if (!_btnLocation.selectedValue) {
        [[JDFacade facade] alert:NSLocalizedString(@"지역을 선택해주세요", @"지역을 선택해주세요")];
    }
    return _btnLocation.selectedValue;
}


- (void)btnConfirmTouched:(id)sender {

    //1.Validate
    if (![self validateCondition]) {
        return;
    }

    [super btnConfirmTouched:sender];
}

@end
