//
//  RulesAddViewController.m
//  kneet2
//
//  Created by Jason Lee on 11/20/15.
//  Copyright © 2015 ntels. All rights reserved.
//

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

#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomImageView.h"
#import "CustomTableView.h"

#import "CustomCheckBox.h"
#import "CustomTextView.h"
#import "CustomTextField.h"
#import "UIImageView+WebCache.h"
#import "ValidateUtil.h"

#import "DeviceSelectPopupView.h"
#import "DeviceNodePopupView.h"
#import "TriggerSelectPopupView.h"

#import "RulesConditionViewController.h"
#import "RulesAddViewController.h"
#import "RulesAddCompleteViewController.h"
#import "RulesDetailViewController.h"
#import "RulesViewController.h"
#import "TimePickerPopupView.h"
#import "DaylightPopupView.h"
#import "ExternHeatPopupView.h"

@implementation RulesAddTitleTableViewCell

@end

@implementation RulesAddHeaderTableViewCell

@end

@implementation RulesAddTableViewCell

@end


@implementation RulesAddPushTableViewCell


@end

@implementation RulesAddConditionHeaderTableViewCell


@end

@implementation RulesAddConditionTableViewCell


@end

@implementation RulesAddFooterTableViewCell

@end

@interface RulesAddViewController () <CustomTextViewDelegate> {
    NSMutableArray<ItemModel> *_triggerDevices, *_actionDevices, *_conditionDevices;
    
    BOOL _isNotFirstLoading, _hasCondition;
    NSMutableArray *_arrayForHeader, *_arrayForFooter;
    
    CustomTextField *_txtRuleTitle;
    CustomTextView *_txvMessage;
    CustomButton *_btnTriggerAdd, *_btnPushAdd;
    
    CustomCheckBox *_chkConditions;
    
    RulesConditionViewController *_rcv;
}

@property (strong, nonatomic) NSMutableArray<ItemModel> *triggers;
@property (strong, nonatomic) NSMutableArray<ItemModel> *actions;
@property (strong, nonatomic) NSMutableArray<ItemModel> *conditions;

@end


#pragma mark - Class Definition

@implementation RulesAddViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initProperties];
    [self initUI];
    [self prepareViewDidLoad];
}


- (void)cloneSubItemsForItemSubType:(NSArray<ItemModel> *)items {
    
    for (ItemModel *item in items) {
        if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            //기존 아이템을 그대로 사용함.
            for (ItemSubModel *subItem in item.subItems) {
                [[JDFacade facade] setRadioButtonStatus:@YES object:subItem];
                [[JDFacade facade] setCheckBoxStatus:@YES object:subItem];
            }
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
            item.pushes = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
            item.subItems = nil;

        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
            item.timers = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
            item.subItems = nil;
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
            item.daylights = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
            item.subItems = nil;
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
            item.heats = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
            item.subItems = nil;
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//더울때/추울때 경우,
            //기존 아이템을 그대로 사용함.
        }
    }
}


- (void)setRefRuleDetail:(RuleDetailModel *)refRuleDetail {

    
    _refRuleDetail = refRuleDetail;
    
    _triggers = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_refRuleDetail.triggers copyItems:YES];
    _actions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_refRuleDetail.actions copyItems:YES];
    _conditions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_refRuleDetail.conditions copyItems:YES];
    
    [self cloneSubItemsForItemSubType:_triggers];
    [self cloneSubItemsForItemSubType:_actions];
    [self cloneSubItemsForItemSubType:_conditions];
    
    _hasCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeHomeMode];
    _hasCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeDueDate] ? YES : _hasCondition;
    _hasCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice] ? YES : _hasCondition;
}

- (void)initProperties {
    _arrayForHeader = [[NSMutableArray alloc] init];
    _arrayForFooter = [[NSMutableArray alloc] init];

    if (!_triggers) {
        _triggers = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
    }
    
    if (!_actions) {
        _actions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
    }
    if (!_conditions) {
        _conditions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
    }
}

- (void)initUI {
    [self initTableViewAsDefaultStyle:_tableView];
    
    if (_refRuleDetail) {
        _lblTitle.text = @"규칙 편집";
    }
}

- (void)prepareViewDidLoad {
    [self requestDeviceListForAction:ksItemTypeCodeTrigger];
}


#pragma mark - Main Logic

- (void)requestDeviceListForAction:(NSString *)typeCode {
    //parameters
    NSDictionary *parameter = @{@"item_type_code": typeCode};
    
    NSString *path = [NSString stringWithFormat:API_GET_ITEM_DEVICES, ksItemTypeCodeAction];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[ItemListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        ItemListModel *fetchedItemList = (ItemListModel *)responseObject;
        
        if (fetchedItemList && fetchedItemList.list && fetchedItemList.list.count) {//API 성공 ,
            
            if ([typeCode isEqualToString:ksItemTypeCodeAction]) {
                _actionDevices = fetchedItemList.list;

                if (_refRuleDetail) {//편집일 경우,
                    ItemModel *actionDevice = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
                    [self matchValueOfDevices:actionDevice devices:_actionDevices];
                }
            } else {
                _triggerDevices = fetchedItemList.list;
                _conditionDevices = [(NSMutableArray<ItemModel> *)[NSMutableArray alloc] initWithArray:_triggerDevices copyItems:YES];
                
                if (_refRuleDetail) {//편집일 경우,
                    ItemModel *triggerDevice = [_triggers objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
                    ItemModel *conditionDevice = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
                    
                    [self matchValueOfDevices:triggerDevice devices:_triggerDevices];
                    [self matchValueOfDevices:conditionDevice devices:_conditionDevices];
                }
                
                [self requestDeviceListForAction:ksItemTypeCodeAction];
            }
            
        }
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)matchValueOfDevices:(ItemModel *)deviceItem devices:(NSMutableArray<ItemModel> *)devices {
    
    for (ItemSubModel *subItem in deviceItem.subItems) {
        NSArray *matchedArray = [devices matchedArrayInSubArrays:@"subItems" predicateFormat:@"sourceId == %@ && sourceSubId == %@", subItem.sourceId, subItem.sourceSubId];
        if (matchedArray.count) {
            ItemSubModel *matchedSubItem = matchedArray.firstObject;
            [[JDFacade facade] setRadioButtonStatus:@YES object:matchedSubItem];
            
            CmdClsValueModel *pCmdClsValue = [matchedSubItem.cmdclsValueList objectKey:@"cmdclsValue" eqaulToString:subItem.cmdclsValue];
            [[JDFacade facade] setRadioButtonStatus:@YES object:pCmdClsValue];
        }
    }
}

- (void)requestRegisterRule {
    
    NSArray *triggers       = [self items:_triggers];
    NSArray *actions        = [self items:_actions];
    
    BOOL hasConditionForRegister = [_conditions matchedArrayInSubArrays:@"subItems" predicateFormat:@"conditionTypeCode == %@", @"09"].count || _chkConditions.checked;
    NSArray *conditions     = hasConditionForRegister ? [self conditions:_conditions] : nil;
    
    //validate
    if (!triggers || !triggers.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"실행할 때를 선택하세요", @"실행할 때를 선택하세요")];
        return;
    }
    
    if (!actions || !actions.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"실행할 장치를 선택하세요", @"실행할 장치를 선택하세요")];
        return;
    }
    
    //parameters
    NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"rule_name" : _txtRuleTitle.text,
                                @"use_yn" : ksYES,
                                @"triggers": triggers ? triggers : [NSNull null],
                                @"actions": actions ? actions : [NSNull null]}];
    if (conditions) {
        [parameter setObject:conditions forKey:@"conditions"];
    }
    
    
    NSString *path = [NSString stringWithFormat:API_POST_RULE];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[RuleModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        RuleModel *newRule = (RuleModel *) responseObject;
        
        if (newRule) {//API 성공 ,
            
            ItemModel *item = _triggers.firstObject;
            if (item) {
                newRule.ruleName = _txtRuleTitle.text;
                newRule.triggerItemSubTypeCode = item.itemSubTypeCode;
            }
            
            RulesAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddCompleteViewController" storyboardName:@"Rules"];
            vc.refRule = newRule;
            vc.providesPresentationContextTransitionStyle = YES;
            vc.definesPresentationContext = YES;
            
            [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
            
            [self presentViewController:vc animated:YES completion:nil];
            
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestModifyRule {
    
    NSArray *triggers       = [self items:_triggers];
    NSArray *actions        = [self items:_actions];
    
    
    BOOL hasConditionForRegister = [_conditions matchedArrayInSubArrays:@"subItems" predicateFormat:@"conditionTypeCode == %@", @"09"].count || _chkConditions.checked;
    NSArray *conditions     = hasConditionForRegister ? [self conditions:_conditions] : nil;
    
    //validate
    if (!triggers || !triggers.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"실행할 때를 선택하세요", @"실행할 때를 선택하세요")];
        return;
    }
    
    if (!actions || !actions.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"실행할 장치를 선택하세요", @"실행할 장치를 선택하세요")];
        return;
    }
    
    //parameters
    NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"rule_name" : _txtRuleTitle.text,
                                                                                     @"use_yn" : ksYES,
                                                                                     @"triggers": triggers ? triggers : [NSNull null],
                                                                                     @"actions": actions ? actions : [NSNull null]}];
    if (conditions) {
        [parameter setObject:conditions forKey:@"conditions"];
    }
    
    NSString *path = [NSString stringWithFormat:API_POST_RULE_MODIFY, _refRuleDetail.homegrpRuleId];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[RuleModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        RuleModel *rule = (RuleModel *) responseObject;
        
        if (rule) {//API 성공
            
            RulesDetailViewController *vc = [[JDFacade facade] viewControllerOnPresentingViewController:self viewControllerClass:[RulesDetailViewController class]];
            if (vc) {
                [vc requestRuleDetail];
            } else {
                RulesViewController *rvc = [[JDFacade facade] viewControllerOnPresentingViewController:self viewControllerClass:[RulesViewController class]];
                [rvc prepareViewDidLoad];
            }
            
            [self dismissViewControllerAnimated:YES completion:^{
                [[JDFacade facade] toast:@"편집을 완료합니다"];
            }];
        }
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

//아이템 배열을 리턴함.
- (NSArray *)items:(NSArray<ItemModel> *)items {
    
    //triggers, actions, conditions
    
    NSMutableArray *rItems = [[NSMutableArray alloc] init];
    
    for (ItemModel *item in items) {
        
        NSDictionary *dic = nil;
        NSMutableArray *subItems = [[NSMutableArray alloc] init];
        
        NSArray *pdevices   = [self subItemsForType:item.subItems itemSubType:ksItemSubTypeCodeDevice];
        NSArray *pushes     = [self subItemsForType:item.pushes itemSubType:ksItemSubTypeCodeAppPush];
        NSArray *timers     = [self subItemsForType:item.timers itemSubType:ksItemSubTypeCodeTimer];
        NSArray *daylights  = [self subItemsForType:item.daylights itemSubType:ksItemSubTypeCodeDaylight];
        NSArray *heats      = [self subItemsForType:item.heats itemSubType:ksItemSubTypeCodeHeat];
        
        if (pdevices && pdevices.count) {//device
            [subItems addObjectsFromArray:pdevices];
        }
        
        if (pushes && pushes.count) {//push
            [subItems addObjectsFromArray:pushes];
        }
        
        if (timers && timers.count) {//timer
            [subItems addObjectsFromArray:timers];
        }
        
        if (daylights && daylights.count) {//해뜰때/질때
            [subItems addObjectsFromArray:daylights];
        }

        if (heats && heats.count) {//더울떄 / 추울때
            [subItems addObjectsFromArray:heats];
        }
        
        if (subItems.count) {
            dic = @{@"item_name": item.itemName,
                    @"item_sub_type_code": item.itemSubTypeCode,
                    @"item_sub": subItems};
            [rItems addObject:dic];
        }
    }
    
    return rItems;
}

//서브아이템 배열을 리턴함.
- (NSArray *)subItemsForType:(NSArray *)subItems itemSubType:(NSString *)itemSubTypeCode {
    
    NSMutableArray *rSubItems = [[NSMutableArray alloc] init];
    
    if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
        
        NSArray<ItemSubModel> *pdevices = (NSArray<ItemSubModel> *)[subItems matchedArrayByObjectName:ksCustomRadioButtonStatus condition:YES];
        for (ItemSubModel *pdevice in pdevices) {
            NSDictionary *rSubItem = @{@"source_id": pdevice.sourceId,
                                       @"source_sub_id": pdevice.sourceSubId,
                                       @"cmdcls_value": pdevice.cmdclsValue,
                                       @"condition_type_code": pdevice.conditionTypeCode,
                                       @"data_type_code": pdevice.dataTypeCode};
            
            [rSubItems addObject:rSubItem];
        }
        
    } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
        //at once.
        
        for (ItemSubModel *subItem in subItems) {
            NSDictionary *rSubItem = @{@"condition_type_code": subItem.conditionTypeCode,
                                       @"cmdcls_value": subItem.cmdclsValue};
            
            [rSubItems addObject:rSubItem];
        }
        
    } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
        for (ItemSubModel *subItem in subItems) {
            NSDictionary *rSubItem = @{@"hour": subItem.hour,
                                       @"minute": subItem.minute};
            
            [rSubItems addObject:rSubItem];
        }
    } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 일 경우,
        for (ItemSubModel *subItem in subItems) {
            NSDictionary *rSubItem = @{@"source_id": subItem.sourceId,
                                       @"source_sub_id": subItem.sourceSubId};
            
            [rSubItems addObject:rSubItem];
        }
    } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//해뜰때/질때 일 경우,
        for (ItemSubModel *subItem in subItems) {
            NSDictionary *rSubItem = @{@"source_id": subItem.sourceId,
                                       @"condition_type_code": subItem.conditionTypeCode,
                                       @"cmdcls_value": subItem.cmdclsValue};
            
            [rSubItems addObject:rSubItem];
        }
    }
    
    return rSubItems;
}


- (NSArray *)conditions:(NSArray<ItemModel> *)items {//trigger만 해당됨.
    
    //conditions
    NSMutableArray *rConditions = [[NSMutableArray alloc] init];
    
    for (ItemModel *condition in items) {//item = condition
        NSMutableArray *rSubItems = [[NSMutableArray alloc] init];
        
        if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeHomeMode]) {
            for (ItemSubModel *mode in condition.subItems) {
                NSDictionary *rSubItem = @{@"source_id": mode.sourceId,
                                           @"cmdcls_value": mode.cmdclsValue,
                                           @"condition_type_code": mode.conditionTypeCode};
                
                [rSubItems addObject:rSubItem];
            }
        } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDueDate]) {
            for (ItemSubModel *subItem in condition.subItems) {
                NSDictionary *rSubItem = @{@"cmdcls_value": subItem.cmdclsValue,
                                           @"condition_type_code": subItem.conditionTypeCode};
                
                [rSubItems addObject:rSubItem];
            }
        } else if ([condition.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {
            for (ItemSubModel *pdevice in condition.subItems) {
                NSDictionary *rSubItem = @{@"source_id": pdevice.sourceId,
                                           @"source_sub_id": pdevice.sourceSubId,
                                           @"cmdcls_value": pdevice.cmdclsValue,
                                           @"data_type_code": pdevice.dataTypeCode,
                                           @"condition_type_code": pdevice.conditionTypeCode};
                
                [rSubItems addObject:rSubItem];
            }
        } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDaysOfWeek]) {
            for (ItemSubModel *subItem in condition.subItems) {
                NSDictionary *rSubItem = @{@"cmdcls_value": subItem.cmdclsValue,
                                           @"condition_type_code": subItem.conditionTypeCode};
                
                [rSubItems addObject:rSubItem];
            }
        }
        
        if (rSubItems.count) {
            NSDictionary *dic = @{@"item_name": condition.itemName,
                    @"item_sub_type_code": condition.itemSubTypeCode,
                    @"item_sub": rSubItems};
            [rConditions addObject:dic];
        }
    }
    
    return rConditions;
}

#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger count = 0;
    if  (section == 0) {//title
        count = 1;
        
    } else if (section == 1) {//triggers
        count = _triggers && _triggers.count ? _triggers.count : 0;
        
    } else if (section == 2) {//actions
        ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
        count = deviceItem.subItems && deviceItem.subItems.count ? deviceItem.subItems.count : 0;
        
    } else if (section == 3) {//push-message
        ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
        count = pushItem.pushes && pushItem.pushes.count ? pushItem.pushes.count : 0;
        
    } else if (section == 4) {//conditions
        count = _chkConditions.checked || _hasCondition ? 1 : 0;
    }
    
    return count;
}

- (NSString *)headerTitleForSection:(NSInteger)section {
    NSString *title = nil;
    
    if (section == 1) {//trigger
        title = @"이 때가 되면";
        if (_triggers && _triggers.count) {
            ItemModel *item = _triggers[0];
            
            if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {
                title = @"장치 상태가 바뀔 때";
            } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {
                title = @"이 시간마다";
            } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {
                title = @"더울때 / 추울때";
            } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {
                title = @"해뜰때 / 질때";
            }
        }
        
    } else if (section == 2) {//action
        title = @"이 장치를 실행";
//        title = _actions && _actions.count ? @"선택됨" : title;
    } else if (section == 3) {//pushes
        title = @"알림 메시지";
//        title = _pushes && _pushes.count ? @"선택됨" : title;
    }
    
//    else if (section == 3) {//conditions
//        title = @"추가 조건";
//        title = _triggers && triggers.count ? @"선택됨" : title;
//    }
    return title;
}

- (void)addTargetToHeaderAddButton:(CustomButton *)btnAdd section:(NSInteger)section {
    if (section == 1) {
        _btnTriggerAdd = btnAdd;
        [btnAdd addTarget:self action:@selector(btnAddTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
        
    } else if (section == 2) {
        [btnAdd addTarget:self action:@selector(btnAddActionTouched:) forControlEvents:UIControlEventTouchUpInside];
        
    } else if (section == 3) {
        _btnPushAdd = btnAdd;
        [btnAdd addTarget:self action:@selector(btnAddPushMessageTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil;
    if (!view) {
        if (section == 0) {//title
            view = [[UIView alloc] init];
        } else if (section == 1 || section == 2 || section == 3) {//hide add button or not;

            RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
            hcell.width = IPHONE_WIDTH;
            
            view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
            [view addSubview:hcell];

            hcell.lblTitle.text = [self headerTitleForSection:section];
            
            if (![hcell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
                [self addTargetToHeaderAddButton:hcell.btnAdd section:section];
            }
            
        } else if (section == 4) {//conditions
            RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ConditionHeaderCellIdentifier"];
            hcell.width = IPHONE_WIDTH;
            
            view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
            [view addSubview:hcell];
            
            _chkConditions = hcell.chkConditions;
            
            if (!_isNotFirstLoading) {
                _chkConditions.checked = _hasCondition;
                _isNotFirstLoading = YES;
            }
            
            if (![_chkConditions actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
                [_chkConditions addTarget:self action:@selector(chkConditionsTouched:) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        
        if (_arrayForHeader.count == section) {
            [_arrayForHeader insertObject:view atIndex:section];
        }
    } else {
        
         if (section == 1 || section == 2 || section == 3) {
             RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)view.subviews[0];
             hcell.lblTitle.text = hcell.lblTitle.text = [self headerTitleForSection:section];
             
         } else if (section == 4) {
//             RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)view.subviews[0];
         }
    }
    
    [self checkHeaderButton:section];
    
    return view;
}

- (void)checkHeaderButton:(NSInteger)section {
    
    if (section == 1) {
        _btnTriggerAdd.hidden = self.triggers.count > 0;
    } else if (section == 3) {
        ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
        NSInteger pcount = pushItem.pushes && pushItem.pushes.count ? pushItem.pushes.count : 0;
        _btnPushAdd.hidden = pcount > 0;
    }
}

- (void)chkConditionsTouched:(id)sender {
    [_tableView reloadData];
    
    CustomCheckBox *chkCondition = (CustomCheckBox *)sender;
    
    if (chkCondition.checked) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:4];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01f;
    } else if (section == 4) {
        return 81.0f;
    }
    return 75.0f;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *view = _arrayForFooter.count > section ? _arrayForFooter[section] : nil;
    if (!view) {
        
        RulesAddFooterTableViewCell *hcell = (RulesAddFooterTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"FooterCellIdentifier"];
        hcell.width = IPHONE_WIDTH;
        
        view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
        [view addSubview:hcell];
        
        if (_arrayForHeader.count == section) {
            [_arrayForHeader insertObject:view atIndex:section];
        }
    }
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01f;
    }
    return 15.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0.0f;
    NSInteger section = indexPath.section;
    
    if (section == 0) {//title
        height = 68                                                                        ;
        
    } else if (section == 1) {//triggers
        height = 86;
        
    } else if (section == 2) {//actions
        height = 86;
        
    } else if (section == 3) {//push-message
        height = 115;
        
    } else if (section == 4) {//conditions
        if (!_rcv) {
            _rcv = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesConditionViewController" storyboardName:@"Rules"];
            
            [self addChildViewController:_rcv];
            [_rcv didMoveToParentViewController:self];
        }
        
        height = _rcv.tableHeight;
    }
    
    return height;
}

+ (BOOL)hasDeleteNode:(ItemModel *)deviceItem {
    NSArray *matchedArray = [deviceItem.subItems filteredArrayUsingPredicateFormat:@"deleteYn == %@", ksYES];
    return matchedArray.count;
}

- (void)configureTriggerCell:(RulesAddTableViewCell *)cell item:(ItemModel *)item {
    
    ItemSubModel *subItem = nil;
    NSString *deviceImageFileName = nil;
    
    if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//장치일 경우
        subItem = [item.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
        
        cell.lblItem.text = subItem.sourceName;

        deviceImageFileName = subItem.imageFileName;
        if ([subItem.deleteYn boolValue]) {
            [cell.lblItem setStrikethrough:cell.lblItem.text];
        }
        
        cell.lblSubItem.text = subItem.sourceSubName;
        
        //노드의 액션 값을 세팅함.
        if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
            CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
            cell.lblCondition.text = [DeviceModel contentValueMsgByCmdClsCode:subItem.cmdclsCode cmdclsTypeId:(NSString *)subItem.cmdclsTypeId contentValue:cmdclsValue.cmdclsValue];
        } else {
            if (subItem.cmdclsValueMsg) {
                cell.lblCondition.text = subItem.cmdclsValueMsg;
            } else {
                NSString *condition = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"이상" : @"이하";
                cell.lblCondition.text = [NSString stringWithFormat:@"%@%@ %@", subItem.cmdclsValue, subItem.unit, condition];
            }
        }
        [cell.lblCondition setUnderLine:cell.lblCondition.text];
        cell.lblCondition.hidden = NO;
        
    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {
        
        subItem = item.timers && item.timers.count ? item.timers[0] : nil;
        if (subItem) {
            NSInteger phour = [subItem.hour integerValue];
            NSString *period = phour < 12 ? @"AM" : @"PM";//NSLocalizedString(@"오전", @"오전") : NSLocalizedString(@"오후", @"오후");
            
            if ([period isEqualToString:NSLocalizedString(@"오후", @"오후")]) {
                if (phour > 12) {
                    phour -= 12;
                }
            }
            
            NSString *title = [NSString stringWithFormat:@"%@ %zd:%@", period, phour, subItem.minute];
            
//            NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
            cell.lblItem.text = title;
            cell.lblSubItem.text = [self daysOfWeekAtSubItem];
            
            cell.lblCondition.hidden = YES;
        }
    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {
        
        subItem = item.daylights && item.daylights.count ? item.daylights[0] : nil;
        if (subItem) {
            NSString *title = [subItem.sourceSubId isEqualToString:@"sunriseUtcTime"] ? @"해뜰때" : @"해질때";

            cell.lblItem.text = title;
            cell.lblSubItem.text = [NSString stringWithFormat:@"%@ / %@", subItem.sourceName, [self daysOfWeekAtSubItem]];
            
            cell.lblCondition.hidden = YES;
        }
    }  else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {
        
        subItem = item.heats && item.heats.count ? item.heats[0] : nil;
        if (subItem) {
            NSString *title = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"더울때" : @"추울때";
            
            cell.lblItem.text = title;
            cell.lblSubItem.text = [NSString stringWithFormat:@"%@ / %@℃ / %@", subItem.sourceName, subItem.cmdclsValue, [self daysOfWeekAtSubItem]];
            
            cell.lblCondition.hidden = YES;
        }
    }
    
    if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {
        if (item.imageFileName) {
            [cell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:item.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
        } else {
            [cell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:deviceImageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
        }
    } else {
        cell.imgvIcon.image = [self imageForTrigger:item];
    }
}

- (NSString *)daysOfWeekAtSubItem {
 
    NSString *daysOfWeek = ksEmptyString;
    ItemModel *daysCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeDaysOfWeek];
    if (daysCondition) {
        ItemSubModel *subCondition = daysCondition.subItems[0];
        daysOfWeek = subCondition.daysOfWeek;
    }
    return daysOfWeek;
}

- (UIImage *)imageForTrigger:(ItemModel *)item {
    UIImage *image = nil;
    
    if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
        image = [UIImage imageNamed:@"img_rule_trigger_icon_time"];
        
    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
        image = [UIImage imageNamed:@"img_rule_trigger_icon_sunset"];
        
    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
        image = [UIImage imageNamed:@"img_rule_trigger_icon_temperature"];
    }
    return image;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    
    UITableViewCell *cell = nil;
    
    if (section == 0) {//title
        RulesAddTitleTableViewCell *tcell = (RulesAddTitleTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        
        tcell.txtRuleTitle.text = [tcell.txtRuleTitle.text isEmptyString] && _refRuleDetail ? _refRuleDetail.ruleName : tcell.txtRuleTitle.text;
        if (!_txtRuleTitle) {
            _txtRuleTitle = tcell.txtRuleTitle;
        }
        
        cell = tcell;
        
    } else if (section == 1) {//triggers
        ItemModel *item = _triggers[indexPath.row];
        
        RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
        [self configureTriggerCell:tcell item:item];
        
        tcell.lblItem.textColor = kUITextColor02;
        
        tcell.btnDelete.value = item;
        if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    } else if (section == 2) {//actions
        
        ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
        ItemSubModel *subItem = deviceItem.subItems[indexPath.row];
        
        RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
        tcell.lblItem.text = subItem.sourceName;
        if ([subItem.deleteYn boolValue]) {
            [tcell.lblItem setStrikethrough:tcell.lblItem.text];
        }

        tcell.lblSubItem.text = subItem.sourceSubName;
        tcell.lblItem.textColor = kUITextColor01;
        
        [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:subItem.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
        
        //노드의 액션 값을 세팅함.
        if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
            CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
            tcell.lblCondition.text = cmdclsValue.cmdclsValueMsg;
        } else {
            if (subItem.cmdclsValueMsg) {
                tcell.lblCondition.text = subItem.cmdclsValueMsg;
            } else {
                NSString *condition = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"이상" : @"이하";
                tcell.lblCondition.text = [NSString stringWithFormat:@"%@%@ %@", subItem.cmdclsValue, subItem.unit, condition];
            }
        }
        
        [tcell.lblCondition setUnderLine:tcell.lblCondition.text];
        
        tcell.btnDelete.value = subItem;
        if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteDeviceActionTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
        
    } else if (section == 3) {//push-message
        
        ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
        ItemSubModel *subItem = pushItem.pushes[indexPath.row];
        
        RulesAddPushTableViewCell *tcell = (RulesAddPushTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"PushCellIdentifier"];
        if (!_txvMessage) {
            _txvMessage = tcell.txvMessage;
        }
        
        _txvMessage.delegate = self;
        _txvMessage.text = [_txvMessage.text isEqualToString:_txvMessage.placeHolder] && _refRuleDetail ? subItem.cmdclsValue : _txvMessage.text;
        
        tcell.btnDelete.value = subItem;
        [tcell.btnDelete addTarget:self action:@selector(btnDeletePushActionTouched:) forControlEvents:UIControlEventTouchUpInside];
        
        cell = tcell;

    } else if (section == 4) {//conditions
        RulesAddConditionTableViewCell *tcell = (RulesAddConditionTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"ConditionCellIdentifier"];
        
        if (_chkConditions.checked) {
            if (!tcell.container.subviews.count) {
                if ([self isViewLoaded]) {
                    [_rcv beginAppearanceTransition:YES animated:NO];
                    [tcell.container addSubview:_rcv.view];
                    [_rcv endAppearanceTransition];
                }
            }

            _rcv.conditions = _conditions;
            _rcv.refDevices = _conditionDevices;
            
            tcell.constraintContainerHeight.constant = _rcv.tableHeight;
        }
        
        cell = tcell;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {//triggers
        ItemModel *item = _triggers[0];
        
        if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            ItemSubModel *subItem = item.subItems[indexPath.row];
            [RulesAddViewController modifyTrigger:item subItem:subItem refDevices:_triggerDevices tableView:_tableView];
            
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
            [self modifyTriggerOfTimer:item];
            
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
            [self modifyTriggerOfDaylight:item];
            
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
            [self modifyTriggerOfHeat:item];
        }
        
    } else if (indexPath.section == 2) {//actions
        ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
        if (deviceItem) {
            ItemSubModel *subItem = deviceItem.subItems[indexPath.row];
            [RulesAddViewController modifyAction:subItem refDevices:_actionDevices tableView:_tableView];
        }
    }
}

- (void)modifyTriggerOfTimer:(ItemModel *)item {
    
    TimePickerPopupView *tpopup = [[TimePickerPopupView alloc] initFromNib];
    tpopup.timeTrigger = item;
    tpopup.refConditions = _conditions;
    
    [tpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [_tableView reloadData];
        }
    }];
}


- (void)modifyTriggerOfDaylight:(ItemModel *)item {
    
    DaylightPopupView *dpopup = [[DaylightPopupView alloc] initFromNib];
    dpopup.daylightTrigger = item;
    dpopup.refConditions = _conditions;
    
    [dpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [_tableView reloadData];
        }
    }];
}

- (void)modifyTriggerOfHeat:(ItemModel *)item {
    
    ExternHeatPopupView *epopup = [[ExternHeatPopupView alloc] initFromNib];
    epopup.externHeatTrigger = item;
    epopup.refConditions = _conditions;
    
    [epopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [_tableView reloadData];
        }
    }];
}

+ (void)modifyTrigger:(ItemModel *)trigger subItem:(ItemSubModel *)subItem refDevices:(NSMutableArray<ItemModel> *)refDevices tableView:(CustomTableView *)tableView {
    
    if ([subItem.deleteYn boolValue]) {
        [[JDFacade facade] toast:@"삭제된 장치입니다\r목록에서 제거하세요"];
        return;
    }
    
    ItemModel *deviceItem = [refDevices objectKey:@"sourceId" eqaulToString:subItem.sourceId];
    
    //노드 선택 팝럽.
    DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
    npopup.refDevice = deviceItem;
    npopup.typeCode = ksItemTypeCodeTrigger;
    npopup.isModifyMode = YES;
    
    [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            
            [trigger.subItems removeAllObjects];
            ItemSubModel *fsubItem = [deviceItem.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
            [trigger.subItems addObject:fsubItem];
            
//            subItem.cmdclsCode = matchedSubItem.cmdclsCode;
//            subItem.cmdclsTypeId = matchedSubItem.cmdclsTypeId;
//
//            if (matchedSubItem.cmdclsValueList) {
//                subItem.cmdclsValueList = matchedSubItem.cmdclsValueList;
//
//                CmdClsValueModel *pCmdClsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
//                subItem.cmdclsValue = pCmdClsValue.cmdclsValue;           //CommandClassControlNodeView - 에서 선택됨.
//            }
            
            if (tableView) {
                [tableView reloadData];
            }
        }
    }];
}


+ (void)modifyAction:(ItemSubModel *)subItem refDevices:(NSMutableArray<ItemModel> *)refDevices tableView:(CustomTableView *)tableView {
    
    if ([subItem.deleteYn boolValue]) {
        [[JDFacade facade] toast:@"삭제된 장치입니다\r목록에서 제거하세요"];
        return;
    }
    
    ItemModel *item = [refDevices objectKey:@"sourceId" eqaulToString:subItem.sourceId];
    ItemSubModel *matchedSubItem = [item.subItems objectKey:@"sourceSubId" eqaulToString:subItem.sourceSubId];
    
    //노드 선택 팝럽.
    DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
    npopup.refDevice = item;
    npopup.typeCode = ksItemTypeCodeTrigger;
    npopup.isModifyMode = YES;
    
    [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            subItem.cmdclsCode = matchedSubItem.cmdclsCode;
            subItem.cmdclsTypeId = matchedSubItem.cmdclsTypeId;
            subItem.cmdclsValueList = matchedSubItem.cmdclsValueList;
            CmdClsValueModel *pCmdClsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
            subItem.cmdclsValue = pCmdClsValue.cmdclsValue;           //CommandClassControlNodeView - 에서 선택됨.
            
            if (tableView) {
                
                [tableView reloadData];
            }
        }
    }];
}

#pragma mark - TableView UI Events


- (void)btnAddTriggerTouched:(id)sender {
    
    TriggerSelectPopupView *tpopup = [[TriggerSelectPopupView alloc] initFromNib];
    tpopup.refTriggers = _triggers;
    tpopup.refDevices = _triggerDevices;
    tpopup.refConditions = _conditions;
    
    [tpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            
            [_tableView reloadData];
        }
    }];
}

- (void)btnAddActionTouched:(id)sender {
    DeviceSelectPopupView *dpopup = [[DeviceSelectPopupView alloc] initFromNib];
    dpopup.refDevices = _actionDevices;
    dpopup.typeCode = ksItemTypeCodeTrigger;
    
    [dpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//ok
            DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
            npopup.refDevice = dpopup.selectedDevices[0];
            npopup.typeCode = ksItemTypeCodeTrigger;
            
            [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                //action add
                if (buttonIndex == 0) {//OK
                    
                    ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
                    if (!deviceItem) {//디바이스 아이템이 없을 경우,
                        deviceItem = [[ItemModel alloc] init];
                        deviceItem.itemName = @"이 장치를 실행";
                        deviceItem.itemSubTypeCode = ksItemSubTypeCodeDevice;
                        
                        deviceItem.subItems = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];
                        
                        [_actions addObject:deviceItem];
                    }
                    
                    
                    ItemSubModel *snode = npopup.selectedNode;
                    //존재 여부 확인
                    if (![deviceItem.subItems objectByUsingPredicateFormat:@"sourceId == %@ && sourceSubId == %@", snode.sourceId, snode.sourceSubId]) {
                        [deviceItem.subItems addObject: snode];
                    }
                    
                    [_tableView reloadData];
                }
            }];
        }
    }];
}

- (void)btnAddPushMessageTouched:(id)sender {
    ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
    if (!pushItem) {//디바이스 아이템이 없을 경우,
        pushItem = [[ItemModel alloc] init];
        pushItem.itemName = [JDFacade facade].loginUser.memberId;
        pushItem.itemSubTypeCode = ksItemSubTypeCodeAppPush;
        
        pushItem.pushes = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];
        
        ItemSubModel *push = [[ItemSubModel alloc] init];
        push.conditionTypeCode = @"02";
        
        [pushItem.pushes addObject:push];
        [_actions addObject:pushItem];
    }
    
    [_tableView reloadData];
}


- (void)btnDeleteTriggerTouched:(id)sender {
     CustomButton *btnDelete = (CustomButton *)sender;
    
    ItemModel *item = btnDelete.value;
    if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//장치일 경우
        ItemSubModel *subItem = [item.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
        if (subItem) {
            [[JDFacade facade] setRadioButtonStatus:@NO object:subItem];

            for (CmdClsValueModel *cmdclsValue in subItem.cmdclsValueList) {
                [[JDFacade facade] setRadioButtonStatus:@NO object:cmdclsValue];
                cmdclsValue.isSelected = NO;
            }
        }
    }
    
    if (_triggers && _triggers.count) {
        [_triggers removeAllObjects];
    }
    
    [_tableView reloadData];
}

- (void)btnDeleteDeviceActionTouched:(id)sender {
    CustomButton *btnDelete = (CustomButton *)sender;
    
    ItemSubModel *subItem = (ItemSubModel *)btnDelete.value;
    
    //선택 설정을 초기화
    [[JDFacade facade] setRadioButtonStatus:@NO object:subItem];
    
    for (CmdClsValueModel *cmdclsValue in subItem.cmdclsValueList) {
        [[JDFacade facade] setRadioButtonStatus:@NO object:cmdclsValue];
        cmdclsValue.isSelected = NO;
    }
    
    ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
    [deviceItem.subItems removeObject:subItem];
    
    [_tableView reloadData];
}

- (void)btnDeletePushActionTouched:(id)sender {
    
    ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
    [_actions removeObject:pushItem];
    
    [_tableView reloadData];
}


#pragma mark - CustomTextView Delegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSLog(@"%s\n %zd", __PRETTY_FUNCTION__, textView.text.length);
    return textView.text.length < 120;
}

#pragma mark - UI Events


- (IBAction)btnConfirmTouched:(id)sender {
    [self.view endEditing:YES];
    
    //1.Validate Title
    RulesAddTitleTableViewCell *tcell = (RulesAddTitleTableViewCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; //타이틀 섹션
    
    if (tcell && ![ValidateUtil validateTextfiled:tcell.txtRuleTitle type:ValidateTypeNull title:NSLocalizedString(@"규칙 이름", @"규칙 이름")]) {
        return;
    }
    
    if (tcell.txtRuleTitle.text.length > 40) {
        [[JDFacade facade] alert:@"규칙이름은 최대 40자까지 입력할 수 있습니다"];
        return;
    }
    
    ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
    if (pushItem) {
        if (_txvMessage && [_txvMessage.text isEmptyString]) {//푸시메시지 여부 확인
            [_actions removeObject:pushItem];
        } else if (_txvMessage) {
            ItemSubModel *subItem = pushItem.pushes[0];
            subItem.cmdclsValue = _txvMessage.text;
            
            if (_txvMessage.text.length > 120) {
                [[JDFacade facade] alert:@"알림메시지는 최대 120자까지 입력할 수 있습니다"];
                return;
            }
        }
    }
    
    if (!_refRuleDetail) {//생성
        [self requestRegisterRule];
        
    } else {//수정

        BOOL hasDeleteNode = NO;
        ItemModel *triggerDevice = [_triggers objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
        ItemModel *actionDevice = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
        ItemModel *conditionDevice = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
        
        hasDeleteNode = [RulesAddViewController hasDeleteNode:triggerDevice];
        hasDeleteNode = [RulesAddViewController hasDeleteNode:actionDevice] ? YES : hasDeleteNode;
        hasDeleteNode = [RulesAddViewController hasDeleteNode:conditionDevice] ? YES : hasDeleteNode;
        
        if (hasDeleteNode) {
            [[JDFacade facade] confirm:@"삭제된 장치를 제외 후 저장합니다" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 0) {//OK
                    [self getRidOfDeleteDevices:triggerDevice];
                    [self getRidOfDeleteDevices:actionDevice];
                    [self getRidOfDeleteDevices:conditionDevice];
                    
                    [_tableView reloadData];
                    
                    [self requestModifyRule];
                }
            }];
        } else {
            [self requestModifyRule];
        }
    }
}

//삭제된 장치를 제거함.
- (void)getRidOfDeleteDevices:(ItemModel *)deviceItem {
    
    [deviceItem.subItems enumerateObjectsUsingBlock:^(ItemSubModel *subItem, NSUInteger idx, BOOL * _Nonnull stop) {
        if (subItem.deleteYn) {
            if ([_triggers containsObject:deviceItem]) {
                [_triggers removeObject:deviceItem];
                return;
            }
            [deviceItem.subItems removeObject:subItem];
        }
    }];
}

- (IBAction)btnCancelTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - MemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end