//
//  RulesRegisterViewController.m
//  kneet
//
//  Created by Jason Lee on 3/19/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
@import ObjectiveC.runtime;

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

#import "UIImageView+WebCache.h"
#import "CustomTextField.h"
#import "CustomLabel.h"
#import "CustomImageView.h"
#import "CustomButton.h"
#import "CustomAlertView.h"
#import "CustomRadioGroup.h"
#import "CustomTextView.h"

#import "ValidateUtil.h"

#import "PredefinedDeviceViewController.h"
#import "RegisterModeViewController.h"
#import "RegisterTimerViewController.h"

#import "RulesRegisterViewController.h"
#import "ActionPopTableView.h"
#import "RegisterCmdClsViewController.h"
#import "RegisterPushViewController.h"
#import "RulesViewController.h"

@implementation RulesCreateHeaderTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
}

@end

@interface RulesCreateTableViewCell () <CustomTextViewDelegate> {

}

@property (weak, nonatomic) ItemModel *item;
@end

@implementation RulesCreateTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    ItemSubModel *subItem = _item.pushes[0];
    subItem.cmdclsValue = textView.text;
}

- (IBAction)btnDeleteSubItemsTouched:(id)sender {

//    if ([_item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
//        [_item.predDevices removeAllObjects];
//    } else if ([_item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
//        [_item.modes removeAllObjects];
//    }
//
//    UITableView *tableView = [(RulesRegisterViewController *)[JDFacade facade].currentViewController tableView];
//    if (tableView) {
//        [tableView reloadRowsAtIndexPaths:@[_indexPath] withRowAnimation:UITableViewRowAnimationNone];
//    }
}

@end

@interface RulesCreateTitleTableViewCell () <CustomTextFieldDelegate> {

}

@end
@implementation RulesCreateTitleTableViewCell

- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor = [UIColor clearColor];

    _txtRuleTitle.delegate = self;
    _txtRuleTitle.keyboardType = UIKeyboardTypeDefault;
    _txtRuleTitle.returnKeyType = UIReturnKeyDone;
    
    _txtRuleTitle.placeholder = NSLocalizedString(@"입력", @"입력");
}

- (void)didMoveToSuperview {
    _txtRuleTitle.customTextFieldSuperview = CustomTextFieldSuperviewIsViewController;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {

    self.txtRuleTitle.hidden = YES;
    self.lblRuleTitle.text = [_txtRuleTitle.text isEmptyString] ? _txtRuleTitle.placeholder : _txtRuleTitle.text;

    self.lblRuleTitle.hidden = NO;
    self.imgvItem.hidden = NO;

    //TODO reload tableview?;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    if (self.txtRuleTitle.hidden && selected && animated && ![self.txtRuleTitle isFirstResponder]) {

        self.lblRuleTitle.hidden = YES;
        self.txtRuleTitle.hidden = NO;
        self.imgvItem.hidden = YES;

        [self.txtRuleTitle becomeFirstResponder];
    }
}

@end

@interface RulesRegisterViewController () <UITableViewDelegate, UITableViewDataSource> {

    NSString *_ruleId, *_ruleName, *_predRuleId;
    NSMutableArray<ItemModel> *_triggers, *_actions, *_conditions;
    BOOL _isNotFirstLoading, _isCustomCreation;
    NSMutableArray *_arrayForHeader;
    UIImage *_iconTrigger, *_iconAction;
    ActionPopTableView *_actionPopTableView;
    NSArray<DeviceModel> *_geofencingDeviceList;
}
@end


#pragma mark - Class Definition

@implementation RulesRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {

    
    

    _tableView.dataSource = self;
    _tableView.delegate = self;

    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];

    _tableView.tableFooterView = [[UIView alloc] init]; //this call table events;

    _isNotFirstLoading = YES;

    _iconTrigger = [UIImage imageNamed:@"tp_01_img_rule_rbox_icon_trigger"];
    _iconAction = [UIImage imageNamed:@"tp_01_img_rule_rbox_icon_action"];
    
    //Localization
    [_btnComplete setTitle:NSLocalizedString(@"완성", @"완성") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {

    _isCustomCreation = YES;

    if (!_tmpPredRule && !_tmpRuleDetail) {//자유롭게 만들기
        _predRuleId = @"0";
    } else {
        //사전 정의 씬 상세 정보 조회
        if (!_tmpRuleDetail) {//사전 정의 씬을 불러온 경우,
            _predRuleId = _tmpPredRule.predRuleId;

            [self requestPredefinedRuleDetail];

        } else {//룰을 수정하는 경우,

            _ruleName = _tmpRuleDetail.ruleName;
            _predRuleId = _tmpRuleDetail.predRuleId; //FIXME :

            [self setRuleDetail];
            [self matchRuleDetailWithPredefinedRuleDeatil:_tmpPredRuleDetail];
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.title = !_tmpRuleDetail ? NSLocalizedString(@"홈 규칙 만들기",@"홈 규칙 만들기") : NSLocalizedString(@"홈 규칙 편집", @"홈 규칙 편집");

    if (_isNotFirstLoading) {
        [_tableView reloadData];
    }
}

#pragma mark - Main Logic

- (NSMutableArray<ItemModel> *)triggers {

    NSMutableArray<ItemModel> *tmpTriggers = [(NSMutableArray<ItemModel> *)[NSMutableArray alloc] init];
    for (ItemModel *trigger in _triggers) {
        if ([trigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            if ((trigger.predDevices)) {
//            if ((trigger.predDevices && trigger.predDevices.count)) {
                [tmpTriggers addObject:trigger];
                break;
            }
        } else if ([trigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            if (trigger.modes) {
//            if (trigger.modes && trigger.modes.count) {
                [tmpTriggers addObject:trigger];
                break;
            }
        } else if ([trigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
            if (trigger.timers) {
//            if (trigger.timers && trigger.timers.count) {
                [tmpTriggers addObject:trigger];
                break;
            }
        } else if ([trigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우,
            if (trigger.mobileDevices) {
//            if (trigger.mobileDevices && trigger.mobileDevices.count) {
                [tmpTriggers addObject:trigger];
                break;
            }
        }
    }

    return tmpTriggers && tmpTriggers.count ? tmpTriggers : _triggers;
}

//자유 선택 - 커스텀 씬 생성 시 사용
- (void)addItem:(ItemModel *)item {
    if (!_isCustomCreation)
        return;

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

    if ([_actions indexOfObject:item] == NSNotFound) {
        [_actions addObject:item];
    }

    [_tableView reloadData];
}

- (void)requestPredefinedRuleDetail {
    NSString *path = [NSString stringWithFormat:API_GET_PRERULE_DETAIL, _predRuleId];
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[PredefinedRuleDetailModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        PredefinedRuleDetailModel *predefinedRuleDetail = (PredefinedRuleDetailModel *) responseObject;

        if (predefinedRuleDetail) {//API 성공 ,

            if (!_tmpRuleDetail) {//생성모드일 경우,
                [self setPredefinedRuleDetail:predefinedRuleDetail];

            }
//            else {//수정모드일 경우,
//                [self matchRuleDetailWithPredefinedRuleDeatil:predefinedRuleDetail];
//            }
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

//각 아이템별 카운트를 설정함
- (void)setPredefinedRuleDetail:(PredefinedRuleDetailModel *)predefinedRuleDetail {//각 아이템별 카운트를 설정함

    _triggers   = (NSMutableArray<ItemModel> *)[NSMutableArray arrayWithArray:predefinedRuleDetail.triggers];
    _actions    = (NSMutableArray<ItemModel> *)[NSMutableArray arrayWithArray:predefinedRuleDetail.actions];
    _conditions = (NSMutableArray<ItemModel> *)[NSMutableArray arrayWithArray:predefinedRuleDetail.conditions];

    [_tableView reloadData];
}

+ (ModeModel *)mode:(NSString *)modeId {
    ModeModel *foundedMode = nil;

    for (ModeModel *mode in [JDFacade facade].modeList) {
        if ([modeId isEqualToString:mode.modeId]) {
            foundedMode = mode;
            break;
        }
    }
    return foundedMode;
}

+ (void)setSubItemsFromItem:(NSArray<ItemModel> *)items {
    for (ItemModel *item in items) {//트리거 설정

        NSString *subTypeCode = item.itemSubTypeCode;

        if ([subTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            item.predDevices = (NSMutableArray<PredefinedDeviceModel> *)[[NSMutableArray alloc] init];

            for (ItemSubModel *subItem in item.subItems) {
                PredefinedDeviceModel *pdevice = [[PredefinedDeviceModel alloc] initWithSubItem:subItem];
                [item.predDevices addObject:pdevice];
            }

        } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            item.modes = (NSMutableArray<ModeModel> *)[[NSMutableArray alloc] init];

            for (ItemSubModel *subItem in item.subItems) {
                ModeModel *mode = [[ModeModel alloc] initWithSubItem:subItem];
                [item.modes addObject:mode];
            }

        } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
            item.pushes = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems];
        }
    }
}

- (void)setRuleDetail {//각 아이템별 카운트를 설정함

    _triggers   = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_tmpRuleDetail.triggers copyItems:YES];
    _actions    = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_tmpRuleDetail.actions copyItems:YES];
    _conditions = (NSMutableArray<ItemModel> *)[NSMutableArray arrayWithArray:_tmpRuleDetail.conditions];

    for (ItemModel *item in _triggers) {//트리거
        NSIndexSet *isDeleted = [item.subItems indexesOfObjectsPassingTest:^BOOL(ItemSubModel *subItem, NSUInteger idx, BOOL *stop) {
            return [subItem.deleteYn boolValue];
        }];
        
        [item.subItems removeObjectsAtIndexes:isDeleted];
        if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//집이 변할때 경우,
            [item.predDevices removeObjectsAtIndexes:isDeleted];
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            [item.modes removeObjectsAtIndexes:isDeleted];
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우,
            [item.mobileDevices removeObjectsAtIndexes:isDeleted];
        }
    }
    
    
    for (ItemModel *item in _actions) {//액션
        NSIndexSet *isDeleted = [item.subItems indexesOfObjectsPassingTest:^BOOL(ItemSubModel *subItem, NSUInteger idx, BOOL *stop) {
            return [subItem.deleteYn boolValue];
        }];
        
        [item.subItems removeObjectsAtIndexes:isDeleted];
        if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            [item.predDevices removeObjectsAtIndexes:isDeleted];
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            [item.modes removeObjectsAtIndexes:isDeleted];
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
            [item.pushes removeObjectsAtIndexes:isDeleted];
        }
    }
    
//    [RulesRegisterViewController setSubItemsFromItem:_triggers];
//    [RulesRegisterViewController setSubItemsFromItem:_actions];
//    [RulesRegisterViewController setSubItemsFromItem:_conditions];
}


//룰 수정 시 - 아이템에 사전정의 아이템의 서브타입 코드를 넣어줌, 사전정의 아이템을 추가함.
+ (void)appendItem:(NSMutableArray<ItemModel> *)items withPredefinedRuleItems:(NSArray<ItemModel> *)predItems isRuleMode:(BOOL)isRuleMode {

    NSInteger i = 0;
    for (ItemModel *predItem in predItems) {

        NSInteger indx = [items indexOfObjectPassingTest:^BOOL(ItemModel *obj, NSUInteger idx, BOOL *stop) {
            if (isRuleMode) {//규칙 모드일 경우,
                return [obj.itemSubTypeCode isEqualToString:predItem.itemSubTypeCode];
            } else {//Scene 모드일 경우,
                return [obj.predActionSequence isEqualToString:predItem.predActionSequence];
            }
        }];

        if (indx == NSNotFound) {
            [items insertObject:predItem atIndex:i];
        } else {
            ((ItemModel *)items[i]).itemTypeCode = predItem.itemTypeCode;
        }
        i++;
    }
}

- (void)matchRuleDetailWithPredefinedRuleDeatil:(PredefinedRuleDetailModel *)predRuleDetail {

    [RulesRegisterViewController appendItem:_triggers withPredefinedRuleItems:predRuleDetail.triggers  isRuleMode:YES];
    [RulesRegisterViewController appendItem:_actions withPredefinedRuleItems:predRuleDetail.actions isRuleMode:YES];
    [RulesRegisterViewController appendItem:_conditions withPredefinedRuleItems:predRuleDetail.conditions isRuleMode:YES];

    [_tableView reloadData];
}


//서브아이템 배열을 리턴함.
- (NSArray *)subItemsForType:(NSArray *)subItems itemSubType:(NSString *)itemSubTypeCode {

    NSMutableArray *rSubItems = [[NSMutableArray alloc] init];

    if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
        for (PredefinedDeviceModel *pdevice in subItems) {
            NSDictionary *rSubItem = @{@"source_id": pdevice.deviceId,
                                       @"source_sub_id": pdevice.nodeId,
                                       @"condition_type_code": pdevice.conditionTypeCode ? pdevice.conditionTypeCode : [NSNull null],
                                       @"cmdcls_value": pdevice.cmdclsValue,
                                       @"data_type_code": pdevice.dataTypeCode,
                                       };

            [rSubItems addObject:rSubItem];
        }

    } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
        for (ModeModel *mode in subItems) {
            NSDictionary *rSubItem = @{@"source_id": @"VAR",
                                       @"cmdcls_value": mode.modeId};

            [rSubItems addObject:rSubItem];
        }

    } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
        //at once.

        for (ItemSubModel *subItem in subItems) {
            NSDictionary *rSubItem = @{
                                       @"source_id": subItem.sourceId,
                                       @"cmdcls_value": subItem.cmdclsValue,
                                       @"condition_type_code" : subItem.conditionTypeCode,
                                       @"data_type_code": @"03"};

            [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:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우,
        for (DeviceModel *device in subItems) {
            NSDictionary *rSubItem = @{@"source_id": device.deviceId,
                                       @"source_sub_id": device.nodeId,
                                       @"condition_type_code": device.conditionTypeCode,
                                       @"cmdcls_value": device.cmdclsValue,
                                       @"data_type_code": device.dataTypeCode,
                                       };
            [rSubItems addObject:rSubItem];
        }
    }

    return rSubItems;
}

//아이템 배열을 리턴함.
- (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.predDevices itemSubType:ksItemSubTypeCodeDevice];
        NSArray *modes      = [self subItemsForType:item.modes itemSubType:ksItemSubTypeCodeMode];
        NSArray *pushes     = [self subItemsForType:item.pushes itemSubType:ksItemSubTypeCodeAppPush];
        NSArray *timers     = [self subItemsForType:item.timers itemSubType:ksItemSubTypeCodeTimer];
        NSArray *geofencings = [self subItemsForType:item.mobileDevices itemSubType:ksItemSubTypeCodeGeoFencing];

        if (pdevices && pdevices.count) {//device
            [subItems addObjectsFromArray:pdevices];
        }

        if (modes && modes.count) {//mode
            [subItems addObjectsFromArray:modes];
        }

        if (pushes && pushes.count) {//push
            [subItems addObjectsFromArray:pushes];
        }

        if (timers && timers.count) {//timer
            [subItems addObjectsFromArray:timers];
        }

        if (geofencings && geofencings.count) {//geofence
            [subItems addObjectsFromArray:geofencings];
        }

        if (subItems.count) {
            dic = @{@"pred_item_sequence": item.predItemSequence,
                    @"item_name": item.itemName,
                    @"item_sub_type_code": item.itemSubTypeCode,
                    @"item_sub": subItems};
            [rItems addObject:dic];
        }
    }

    return rItems;
}


- (NSArray *)conditions:(NSArray<ItemModel> *)items {//trigger만 해당됨.

    //conditions
    NSMutableArray *rConditions = [[NSMutableArray alloc] init];

    for (ItemModel *item in items) {
        ItemSubModel *subItem = nil;

        if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            subItem = item.predDevices && item.predDevices.count ? item.predDevices[0] : nil;
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            subItem = item.modes[0];

        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
            subItem = item.timers[0];
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우,
            subItem = item.mobileDevices && item.mobileDevices.count ? item.mobileDevices[0] : nil;
        }

        for (ItemModel *condition in subItem.conditions) {//컨디션 여부
            ItemModel *copyCondition = [condition copy];
            
            
            for (ItemSubModel *subCondition in copyCondition.subItems) {
                subCondition.cmdclsValueMsg = nil;
                subCondition.dueDate = nil;
                subCondition.daysOfWeek = nil;
                subCondition.dueTime = nil;
                subCondition.homeModes = nil;
                subCondition.externHeat = nil;
            }

            [rConditions addObject:[copyCondition toDictionary]];
        }
    }

    return rConditions;
}


- (void)requestRegisterRule {

    NSArray *triggers       = [self items:[self triggers]];
    NSArray *actions        = [self items:_actions];
    NSArray *conditions     = [self conditions:[self triggers]];

    //validate
    if (!triggers || !triggers.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"선택된 트리거가 없습니다", @"선택된 트리거가 없습니다")];
        return;
    }

    if (!actions || !actions.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"액션이 없습니다", @"액션이 없습니다")];
        return;
    }

    //1.트리거 == 모드 && 액션 == 모드
    for (ItemModel *trigger in [self triggers]) {
        if ([trigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {
            for (ItemModel *action in _actions) {
                if ([action.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {
                    [[JDFacade facade] alert:NSLocalizedString(@"'홈 모드가 바뀔 때'인 경우에는 실행 목록에서 '홈 모드 변경'을 선택할 수 없습니다", @"'홈 모드가 바뀔 때'인 경우에는 실행 목록에서 '홈 모드 변경'을 선택할 수 없습니다")];
                    return;
                }
            }
        }
    }
    
    for (ItemModel *action in _actions) {
        if ([action.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {
            for (NSDictionary *condition in conditions) {//컨디션에 모드가 있을 경우,
                if ([condition[@"item_sub_type_code"] isEqualToString:ksItemSubTypeCodeMode]) {
                    [[JDFacade facade] alert:NSLocalizedString(@"'홈 모드 변경'인 경우에는 추가 조건에서 '홈 모드'를 선택할 수 없습니다", @"'홈 모드 변경'인 경우에는 추가 조건에서 '홈 모드'를 선택할 수 없습니다")];
                    return;
                }
            }     
        }
    }


    //parameters
    NSDictionary *parameter = @{@"pred_rule_id" : _predRuleId,
                                @"rule_name" : _ruleName,
                                @"use_yn" : ksYES,
                                @"triggers": triggers ? triggers : [NSNull null],
                                @"actions": actions ? actions : [NSNull null],
                                @"conditions": conditions ? conditions : [NSNull null]};

    NSString *path = [NSString stringWithFormat:API_POST_RULE];

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

        JDJSONModel *result = (JDJSONModel *) responseObject;

        if (result) {//API 성공 ,
            [[JDFacade facade] toast:NSLocalizedString(@"등록되었습니다", @"등록되었습니다")];
            [[JDFacade facade] gotoWishMenu:KNMenuIdRules];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


- (void)requestModifyRule {

    NSArray *triggers       = [self items:[self triggers]];
    NSArray *actions        = [self items:_actions];
    NSArray *conditions     = [self conditions:[self triggers]];

    //validate
    //    if (!triggers || !triggers.count || !triggers[@"item_sub"] || ![((NSArray *)triggers[@"item_sub"]) count]) {
    if (!triggers || !triggers.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"트리거가 없습니다", @"트리거가 없습니다")];
        return;
    }

    if (!actions || !actions.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"액션이 없습니다", @"액션이 없습니다")];
        return;
    }

    //1.트리거 == 모드 && 액션 == 모드
    for (ItemModel *trigger in [self triggers]) {
        if ([trigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {
            for (ItemModel *action in _actions) {
                if ([action.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {
                    [[JDFacade facade] alert:NSLocalizedString(@"'홈 모드가 바뀔 때'인 경우에는 실행 목록에서 '홈 모드 변경'을 선택할 수 없습니다", @"'홈 모드가 바뀔 때'인 경우에는 실행 목록에서 '홈 모드 변경'을 선택할 수 없습니다")];
                    return;
                }
            }
        }
    }
    
    
    for (ItemModel *action in _actions) {
        if ([action.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {
            for (NSDictionary *condition in conditions) {//컨디션에 모드가 있을 경우,
                if ([condition[@"item_sub_type_code"] isEqualToString:ksItemSubTypeCodeMode]) {
                    [[JDFacade facade] alert:NSLocalizedString(@"'홈 모드 변경'인 경우에는 추가 조건에서 '홈 모드'를 선택할 수 없습니다", @"'홈 모드 변경'인 경우에는 추가 조건에서 '홈 모드'를 선택할 수 없습니다")];
                    return;
                }
            }     
        }
    }

    //parameters
    NSDictionary *parameter = @{@"pred_rule_id" : _predRuleId,
                                @"rule_name" : _ruleName,
                                @"use_yn" : ksYES,
                                @"triggers": triggers ? triggers : [NSNull null],
                                @"actions": actions ? actions : [NSNull null],
                                @"conditions": conditions ? conditions : [NSNull null]};

    NSString *path = [NSString stringWithFormat:API_POST_RULE_MODIFY, _tmpRuleDetail.homegrpRuleId];

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

        RuleModel *rule = (RuleModel *) responseObject;

        if (rule) {//API 성공 ,
            _tmpRuleDetail.ruleId = rule.ruleId;
            _tmpRuleDetail.ruleName = _ruleName;

            RulesViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[RulesViewController class]];
            [vc prepareViewDidLoad];

            [[JDFacade facade] toast:@"수정되었습니다."];
            [self.navigationController popViewControllerAnimated:YES];
        }

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


#pragma mark - UITableView DataSource & Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSString *)titleForSectionHeader:(NSInteger)section {
    NSString *title = nil;
    switch (section) {
        case 0:
            title = NSLocalizedString(@"언제 실행할까요?", @"언제 실행할까요?");
            break;
        case 1:
            title = NSLocalizedString(@"무엇을 실행할까요?", @"무엇을 실행할까요?");
            break;
        case 2:
            title = NSLocalizedString(@"규칙에 이름을 붙여주세요", @"규칙에 이름을 붙여주세요");
            break;
    }
    return title;
}

- (UIImage *)imageForSection:(NSInteger)section {
    UIImage *image = nil;
    switch (section) {
        case 0:
            image = _iconTrigger;
            break;
        case 1:
            image = _iconAction;
            break;
        case 2:
            break;
    }
    return image;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil;
    if (!view) {
        RulesCreateHeaderTableViewCell *hcell = (RulesCreateHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
        CGFloat height = [self tableView:tableView heightForHeaderInSection:section];
        hcell.frame = CGRectMake(0, 0, IPHONE_WIDTH, height);

        if (section == 0) {
            hcell.imgvTop.hidden = YES;
            hcell.constraintHeaderTitleTop.constant = 10;
        }

        view = [[UIView alloc] initWithFrame:hcell.frame];
        [view addSubview:hcell];
        hcell.lblHeaderTitle.text = [self titleForSectionHeader:section];

        [_arrayForHeader insertObject:view atIndex:section];
    }

    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    if (section == 0) {
        return 65.0f;
    }
    return 72.0f;
}

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 0;
    if (section == 2) {
        count = 1;
    } else if (section == 0) {
        count = [self triggers].count;
    } else if (section == 1) {
        count = _actions.count + _isCustomCreation;
    }
//    else if (section == 2) {
//        count = _conditions.count;
//    }

    return count;
}

+ (CGFloat)heightForSubItems:(ItemModel *)item isTrigger:(BOOL)isTrigger {

    NSString *subTypeCode = item.itemSubTypeCode;

    CGFloat width = IPHONE_WIDTH - 80;
    CustomLabel *lblTemp = [[CustomLabel alloc] initWithFrame:CGRectMake(0, 0, width, 20)];
    lblTemp.font = [UIFont systemFontOfSize:kUIFontSize06];
    lblTemp.numberOfLines = 0;
    CGFloat titleHeight = 0.0f;

    if (isTrigger) {//triggers
        CGFloat twidth = IPHONE_WIDTH - 80 - 25;
        CustomLabel *lblTitle = [[CustomLabel alloc] initWithFrame:CGRectMake(0, 0, twidth, 55)];
        lblTitle.font = [UIFont systemFontOfSize:kUIFontSize01];
        lblTitle.numberOfLines = 0;

        //타이틀 사이즈를 구함.
        ItemSubModel *subItem = [RulesRegisterViewController subItemAndfillTriggerTitle:lblTitle item:item];
        if (subItem) {//삭제 버튼이 있을 경우,
            twidth = IPHONE_WIDTH - 80 - 25 - 30;
        }
        
        titleHeight = [CommonUtil getSizeFromString:lblTitle.text font:lblTitle.font width:twidth].height;
        titleHeight = titleHeight < 55.0f ? 0.0f : titleHeight - 55.0f; //원래 차지하는 사이즈만큼 빼줌.

        for (ItemModel *condition in subItem.conditions) {
            //TODO : 컨디션은 1개의 서브 컨디션을 갖음 (0.6 버전)
            ItemSubModel *subCondition = condition.subItems[0];
            [self fillConditionSubItemToLabel:lblTemp item:subCondition itemSubTypeCode:condition.itemSubTypeCode];
        }

    } else {//actions
        if ([subTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            [RulesRegisterViewController fillPredDeviceSubItemsToLabel:lblTemp item:item];

        } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            [RulesRegisterViewController fillModeSubItemsToLabel:lblTemp item:item];

        } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
            
            CGFloat twidth = IPHONE_WIDTH - 80 - 25;
            CustomLabel *lblTitle = [[CustomLabel alloc] initWithFrame:CGRectMake(0, 0, twidth, 55)];
            lblTitle.font = [UIFont systemFontOfSize:kUIFontSize01];
            lblTitle.numberOfLines = 0;
            
            //타이틀 사이즈를 구함.
            if (item.pushes && item.pushes.count) {//삭제 버튼이 있을 경우,
                twidth = IPHONE_WIDTH - 80 - 25 - 30;
            }
            
            titleHeight = [CommonUtil getSizeFromString:lblTitle.text font:lblTitle.font width:twidth].height;
            titleHeight = titleHeight < 55.0f ? 0.0f : titleHeight - 55.0f; //원래 차지하는 사이즈만큼 빼줌.

            [RulesRegisterViewController fillPushesSubItemsToLabel:lblTemp item:item];
        }
    }

    CGFloat height = [CommonUtil getSizeFromAttributeString:lblTemp.attributedText width:width].height;
    return height + titleHeight; //add margin
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0 || indexPath.section == 1) {
        //calcualate subItemsText
        NSArray *items = nil;
        if (indexPath.section == 0) {
            items = [self triggers];

        } else if (indexPath.section == 1) {
            items = _actions;

            if (indexPath.row == _actions.count) {//자유롭게 만들기 셀 (액션 추가)
                height = 60.0f;
                return height;
            }
        }

        ItemModel *item = items[indexPath.row];
        CGFloat adjustHeight = [RulesRegisterViewController heightForSubItems:item isTrigger:indexPath.section == 0];
        adjustHeight = adjustHeight > 0 ? adjustHeight + 15 + 20 : adjustHeight;

        height = 60 + adjustHeight;

    } else if (indexPath.section == 2) {
        height = 89.0f;
    }

    return height;
}


+ (void)fillPredDeviceSubItemsToLabel:(CustomLabel *)label item:(ItemModel *)item {
    for (PredefinedDeviceModel *pdevice in item.predDevices) {

        NSMutableAttributedString *subText = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];

        NSString *prefix = [item.predDevices.firstObject isEqual:pdevice] ? ksEmptyString: @", ";
        NSString *deviceName = [NSString stringWithFormat:@"%@(%@)", pdevice.deviceName, pdevice.nodeName];
        NSString *text = [NSString stringWithFormat:@"%@● %@", prefix, deviceName];

        NSDictionary *attrColor = @{NSForegroundColorAttributeName : [pdevice.deleteYn boolValue] ? kUITextColor02 : kUITextColor01};
        
        NSMutableAttributedString *attrDeviceName = [[NSMutableAttributedString alloc] initWithString:text];
        [attrDeviceName addAttributes:attrColor range:[text rangeOfString:deviceName]];
        if ([pdevice.deleteYn boolValue]) {
            NSDictionary *attrStrike = @{NSStrikethroughStyleAttributeName: @(NSUnderlineStyleSingle)};
            [attrDeviceName addAttributes:attrStrike range:[text rangeOfString:deviceName]];              
        }
        
        [subText appendAttributedString:attrDeviceName];

        label.attributedText = subText;
    }
}

+ (void)fillModeSubItemsToLabel:(CustomLabel *)label item:(ItemModel *)item {
    for (ModeModel *mode in item.modes) {

        NSMutableAttributedString *subText = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];

        NSString *prefix = [item.modes.firstObject isEqual:mode] ? ksEmptyString: @", ";
        NSString *modeName = [NSString stringWithFormat:@"%@● %@", prefix, mode.modeName];

        [subText appendAttributedString:[[NSAttributedString alloc] initWithString:modeName]];

        label.attributedText = subText;
    }
}


+ (void)fillPushesSubItemsToLabel:(CustomLabel *)label item:(ItemModel *)item {
    if (item.pushes && item.pushes.count) {
        ItemSubModel *push = item.pushes.firstObject;
        
        NSMutableAttributedString *subText = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
        [subText appendAttributedString:[[NSAttributedString alloc] initWithString:push.cmdclsValue]];
        
        label.attributedText = subText;
    }
}

+ (void)fillConditionSubItemToLabel:(CustomLabel *)label item:(ItemSubModel *)subItem itemSubTypeCode:(NSString *)itemSubTypeCode {

    NSMutableAttributedString *subText = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];

    NSString *prefix = [label.attributedText.string isEmptyString] ? ksEmptyString : @"\n";
    NSString *cname = nil;

    if ([itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDueDate]) {//기간
        cname = NSLocalizedString(@"기간", @"기간");
    } else if ([itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDaysOfWeek]) {//요일
        cname = NSLocalizedString(@"요일", @"요일");
    } else if ([itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDueTime]) {//시간
        cname = NSLocalizedString(@"시간", @"시간");
    } else if ([itemSubTypeCode isEqualToString:ksConditionSubTypeCodeHomeMode]) {//홈모드
        cname = NSLocalizedString(@"홈모드", @"홈모드");
    } else if ([itemSubTypeCode isEqualToString:ksConditionSubTypeCodeExternHeat]) {//바깥온도
        cname = NSLocalizedString(@"지역온도", @"지역온도");
    }

    NSString *deviceName = [NSString stringWithFormat:@"%@ ➜ %@ : %@", prefix, cname, subItem.cmdclsValueMsg];
    [subText appendAttributedString:[[NSAttributedString alloc] initWithString:deviceName]];

    label.attributedText = subText;
}

+ (ItemSubModel *)subItemAndfillTriggerTitle:(CustomLabel *)label item:(ItemModel *)item {

    NSString *subTypeCode = item.itemSubTypeCode;
    ItemSubModel *subItem = nil;

    if ([subTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,

        PredefinedDeviceModel *pdevice = item.predDevices && item.predDevices.count ? item.predDevices[0] : nil;
        if (pdevice) {
            NSDictionary *attrColor = @{NSForegroundColorAttributeName : [pdevice.deleteYn boolValue] ? kUITextColor02 : kUITextColor01};
            
            
            NSString *condition = [pdevice.conditionTypeCode isEqualToString:@"02"] ? NSLocalizedString(@"미만 시", @"미만 시") : ksEmptyString;
            condition = [pdevice.conditionTypeCode isEqualToString:@"04"] ? NSLocalizedString(@"초과 시", @"초과 시") : condition;
            
            NSString *deviceName = [NSString stringWithFormat:@"\n%@ : %@ %@ %@", pdevice.deviceName, pdevice.nodeName, pdevice.cmdclsValue, condition];
            NSMutableAttributedString *attrDeviceName = [[NSMutableAttributedString alloc] initWithString:deviceName];
            [attrDeviceName addAttributes:attrColor range:[deviceName rangeOfString:deviceName]];
            if ([pdevice.deleteYn boolValue]) {
                NSDictionary *attrStrike = @{NSStrikethroughStyleAttributeName: @(NSUnderlineStyleSingle)};
                [attrDeviceName addAttributes:attrStrike range:[deviceName rangeOfString:deviceName]];              
            }
            
            NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", item.itemName]];
            [titleText appendAttributedString:attrDeviceName];
            
            NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
            [titleText setAttributes:titleColor range:[item.itemName rangeOfString:item.itemName]];
            
            label.attributedText = titleText;
            subItem = pdevice;
        }
        
    } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//홈모드일 경우,
        
        ModeModel *mode = item.modes && item.modes.count ? item.modes[0] : nil;
        if (mode) {
            NSString *modeTitle = [NSString stringWithFormat:NSLocalizedString(@"[%@]로 바뀔 때", @"[%@]로 바뀔 때"), mode.modeName];
            
            NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
            label.attributedText = [[NSMutableAttributedString alloc] initWithString:modeTitle attributes:titleColor];
            subItem = mode;
        }
        
    } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,

        subItem = item.timers && item.timers.count ? item.timers[0] : nil;
        if (subItem) {
            NSInteger phour = [subItem.hour integerValue];
            NSString *period = phour < 12 ? NSLocalizedString(@"오전", @"오전") : NSLocalizedString(@"오후", @"오후");

            if ([period isEqualToString:NSLocalizedString(@"오후", @"오후")]) {
                phour -= 12;
            }

            NSString *title = [NSString stringWithFormat:NSLocalizedString(@"%@ %zd시 %@분", @"%@ %zd시 %@분"), period, phour, subItem.minute];
            
            NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
            label.attributedText = [[NSMutableAttributedString alloc] initWithString:title attributes:titleColor];
        }
    } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우,

        if (item.mobileDevices && item.mobileDevices.count) {
            NSString *geoMode = nil;
            NSMutableString *fam = [[NSMutableString alloc] init];

            for (DeviceModel *device in item.mobileDevices) {
                if (!geoMode) {
                    subItem = device;
                    geoMode = [device.cmdclsValue isEqualToString:@"TRUE"] ? NSLocalizedString(@"도착할 때", @"도착할 때") : NSLocalizedString(@"출발할 때", @"출발할 때");
                }

                NSString *prefix = [fam isEmptyString] ? @"" : @", ";
                [fam appendFormat:@"%@%@ (%@)", prefix, device.nickname, device.deviceName];
            }
            
            NSString *title = [NSString stringWithFormat:@"%@\n%@", geoMode, fam];
            
            NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
            NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:title];
            [attrTitle setAttributes:titleColor range:[title rangeOfString:geoMode]];
            
            label.attributedText = attrTitle;
        }
    }
    return subItem;
}

+ (void)fillCell:(RulesCreateTableViewCell *)cell item:(ItemModel *)item isTrigger:(BOOL)isTrigger {

    cell.lblItemName.attributedText = [[NSAttributedString alloc] initWithString:item.itemName];
    cell.lblSubItems.text = ksEmptyString;
    cell.lblSubItems.hidden = YES;

    NSString *subTypeCode = item.itemSubTypeCode;
    CGFloat titleHeight = 0.0f;
    CGFloat adjustHeight = 0.0f;
    cell.item = item;
    ItemSubModel *subItem = nil;

    if (isTrigger) {//triggers
        subItem = [RulesRegisterViewController subItemAndfillTriggerTitle:cell.lblItemName item:item];
        cell.lblSubItems.hidden = !(subItem.conditions && subItem.conditions.count);
        CGFloat deleteWidth = !subItem ? 0 : 30.0f;
        cell.constraintTitleLabelRight.constant = !subItem ? -20.0f : -50.0f;
        
        titleHeight = [CommonUtil getSizeFromAttributeString:cell.lblItemName.attributedText width:IPHONE_WIDTH - 80 - 25.0f - deleteWidth].height; //padding, image margin
        titleHeight = titleHeight <= 55.0f ? 0.0f : titleHeight - 55.0f;
        cell.btnDeleteSubItems.hidden = !subItem; //트리거가 있는 경우,


        //컨디션이 있을 경우,
        cell.lineview.hidden = cell.lblSubItems.hidden;

        if (!cell.lblSubItems.hidden) {//컨디션이 있을 경우,
            for (ItemModel *condition in subItem.conditions) {
                //TODO : 컨디션은 1개의 서브 컨디션을 갖음 (0.6 버전)
                ItemSubModel *subCondition = condition.subItems[0];
                [self fillConditionSubItemToLabel:cell.lblSubItems item:subCondition itemSubTypeCode:condition.itemSubTypeCode];

                adjustHeight = [CommonUtil getSizeFromAttributeString:cell.lblSubItems.attributedText width:IPHONE_WIDTH - 80].height;
            }
        }

    } else {//actions
        if ([subTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            cell.lblSubItems.hidden = !item.predDevices.count;
            cell.lineview.hidden = cell.btnDeleteSubItems.hidden = cell.lblSubItems.hidden;

            [self fillPredDeviceSubItemsToLabel:cell.lblSubItems item:item];

            adjustHeight = [CommonUtil getSizeFromAttributeString:cell.lblSubItems.attributedText width:IPHONE_WIDTH - 80].height; //subtract left, right margin

        } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            cell.lblSubItems.hidden = !item.modes.count;
            cell.lineview.hidden = cell.btnDeleteSubItems.hidden = cell.lblSubItems.hidden;

            [self fillModeSubItemsToLabel:cell.lblSubItems item:item];

            adjustHeight = [CommonUtil getSizeFromAttributeString:cell.lblSubItems.attributedText width:IPHONE_WIDTH - 80].height;

        } else if ([subTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
            cell.lblSubItems.hidden = !item.pushes.count;
            cell.lineview.hidden = cell.btnDeleteSubItems.hidden = cell.lblSubItems.hidden;
            
            //멤버 표시
            NSMutableAttributedString *pmem = [[NSMutableAttributedString alloc] init];
            for (ItemSubModel *subItem in item.pushes) {
                NSString *prefix = [pmem.string isEmptyString] ? @"\n" : @", ";
                
                NSDictionary *attrColor = @{NSForegroundColorAttributeName : [subItem.deleteYn boolValue] ? kUITextColor02 : kUITextColor01};
                NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", prefix, subItem.sourceName]];
                [attrString addAttributes:attrColor range:[attrString.string rangeOfString:subItem.sourceName]];
                
                if ([subItem.deleteYn boolValue]) {
                    NSDictionary *attrStrike = @{NSStrikethroughStyleAttributeName: @(NSUnderlineStyleSingle)};
                    [attrString addAttributes:attrStrike range:[attrString.string rangeOfString:subItem.sourceName]];              
                }

                [pmem appendAttributedString:attrString];
            }
            
            NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:item.itemName];
            [title appendAttributedString:pmem];
            cell.lblItemName.attributedText = title;
            
            //타이틀 높이를 구함.
            CGFloat deleteWidth = (!item.pushes || !item.pushes.count) ? 0 : 30.0f;
            cell.constraintTitleLabelRight.constant = (!item.pushes || !item.pushes.count) ? -20.0f : -50.0f;
            titleHeight = [CommonUtil getSizeFromAttributeString:cell.lblItemName.attributedText width:IPHONE_WIDTH - 80 - 25.0f - deleteWidth].height; //padding, image margin
            
            titleHeight = titleHeight <= 55.0f ? 0.0f : titleHeight - 55.0f;

            [self fillPushesSubItemsToLabel:cell.lblSubItems item:item];
            adjustHeight = [CommonUtil getSizeFromAttributeString:cell.lblSubItems.attributedText width:IPHONE_WIDTH - 80].height;
        }
        
        if (adjustHeight > 0) {
                        
            NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
            NSMutableAttributedString *attrItemName = [[NSMutableAttributedString alloc] initWithAttributedString:cell.lblItemName.attributedText];
            [attrItemName addAttributes:titleColor range:[item.itemName rangeOfString:item.itemName]];

            cell.lblItemName.attributedText = attrItemName;
        }
    }

    //배경 이미지 설정
    UIImage *bgImage = nil;

    if ([cell.lblSubItems.text isEmptyString]) {//서브아이템이 없을 경우, static title을 가져옴.
//          cell.lblSubItems.text = [ItemModel itemSubTypeString:subTypeCode];

        bgImage = subItem ? [UIImage imageNamed:@"tp_01_img_rule_rbox_bg_active"] : [UIImage imageNamed:@"tp_01_img_rule_rbox_bg"];
        cell.constraintImgvBgHeight.constant = 55.0f + titleHeight;
    } else {
        bgImage = [UIImage imageNamed:@"tp_01_img_rule_rbox_bg_active"];
        cell.constraintImgvBgHeight.constant = 55.0f + titleHeight + adjustHeight + 15 + 20;  //label top, bottom margin add
    }
    [cell.imgvBg setImage:bgImage];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;

//    NSLog(@"%s\n %zd, %zd", __PRETTY_FUNCTION__, indexPath.section, indexPath.row);

    if (indexPath.section == 2) {//타이틀 셀
        RulesCreateTitleTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];

        if (tcell == nil) {
            tcell = [[RulesCreateTitleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TitleCellIdentifier"];
        }

        tcell.txtRuleTitle.text = [tcell.txtRuleTitle.text isEmptyString] ? _ruleName : tcell.txtRuleTitle.text;
        tcell.lblRuleTitle.text = [tcell.txtRuleTitle.text isEmptyString] ? NSLocalizedString(@"입력", @"입력") : tcell.txtRuleTitle.text;

        cell = tcell;

    } else {
        RulesCreateTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

        if (tcell == nil) {
            tcell = [[RulesCreateTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
        }

        NSArray *items = nil;
        if (indexPath.section == 0) {
            items = [self triggers];
        } else if (indexPath.section == 1) {
            items = _actions;

            UIImage *bgImage = [UIImage imageNamed:@"tp_01_img_rule_rbox_bg"];
            tcell.constraintImgvBgHeight.constant = 55.0f;
            [tcell.imgvBg setImage:bgImage];

            if (indexPath.row == _actions.count) {//자유롭게 만들기 셀 (액션 추가)
                tcell.lblItemName.text = NSLocalizedString(@"자유 선택", @"자유 선택");
                tcell.lblSubItems.hidden = YES;
                tcell.imgvItem.image = [self imageForSection:indexPath.section];
                tcell.lineview.hidden = tcell.btnDeleteSubItems.hidden = tcell.lblSubItems.hidden;
                return tcell;
            }
        }
//        else if (indexPath.section == 3) {
//            items = _conditions;
//
//        }

        ItemModel *item = items[indexPath.row];
        [RulesRegisterViewController fillCell:tcell item:item isTrigger:indexPath.section == 0];
        tcell.indexPath = indexPath;
        tcell.btnDeleteSubItems.value = item;

        if (![tcell.btnDeleteSubItems actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnDeleteSubItems addTarget:self action:@selector(btnDeleteSubItemsTouched:) forControlEvents:UIControlEventTouchUpInside];
        }

        tcell.imgvItem.image = [self imageForSection:indexPath.section];
        cell = tcell;

    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 2) { //텍스트필드를 포커스
        RulesCreateTitleTableViewCell *cell = (RulesCreateTitleTableViewCell *)[_tableView cellForRowAtIndexPath:indexPath];
        [cell setSelected:YES animated:YES];

        return;

    } else {
        NSIndexPath *ip = [NSIndexPath indexPathForItem:0 inSection:2]; //텍스트필드를 원상태로 되돌림
        RulesCreateTitleTableViewCell *cell = (RulesCreateTitleTableViewCell *)[_tableView cellForRowAtIndexPath:ip];
        if (!cell.txtRuleTitle.hidden && [cell.txtRuleTitle isFirstResponder]) {
            [cell.txtRuleTitle resignFirstResponder];
        }
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSArray *items = nil;

    if (indexPath.section == 0) {
        items = [self triggers];

    } else if (indexPath.section == 1) {
        items = _actions;

        if (indexPath.row == _actions.count) {//자유롭게 만들기 셀 (액션 추가)

            //FIXME : 매번 로드를 해야되는가?
            if (!_actionPopTableView) {
                _actionPopTableView = [[ActionPopTableView alloc] initFromNib];
                _actionPopTableView.isRuleMode = YES;
            }
            _actionPopTableView.actions = _actions;
            [_actionPopTableView.tableView scrollsToTop];
            [_actionPopTableView show];
            return;
        }
    }
//    else if (indexPath.section == 2) {
//        items = _conditions;
//    }

    ItemModel *item = items[indexPath.row];

    UIViewController *vc = nil;
    if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,

        if (indexPath.section == 0) {//트리거
            RegisterCmdClsViewController *cvc = (RegisterCmdClsViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RegisterCmdClsViewController" storyboardName:@"Rules"];

            cvc.title = [self titleForSectionHeader:indexPath.section];
            cvc.tmpItem = item;

            vc = cvc;

        } else if (indexPath.section == 1){//액션
            PredefinedDeviceViewController *dvc = (PredefinedDeviceViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"PredefinedDeviceViewController" storyboardName:@"Rules"];

            dvc.title = [self titleForSectionHeader:indexPath.section];
            dvc.predRuleId = _predRuleId;
            dvc.tmpItem = item;

            vc = dvc;
        }

    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
        RegisterModeViewController *mvc = (RegisterModeViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RegisterModeViewController" storyboardName:@"Rules"];

        mvc.title = [self titleForSectionHeader:indexPath.section];
        mvc.isTrigger = indexPath.section == 0; //0 == trigger
        mvc.tmpItem = item;

        vc = mvc;

    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
        RegisterPushViewController *tvc = (RegisterPushViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RegisterPushViewController" storyboardName:@"Rules"];

        tvc.title = [self titleForSectionHeader:indexPath.section];
        tvc.tmpItem = item;

        vc = tvc;
    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
        RegisterTimerViewController *tvc = (RegisterTimerViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RegisterTimerViewController" storyboardName:@"Rules"];

        tvc.title = [self titleForSectionHeader:indexPath.section];
        tvc.tmpItem = item;

        vc = tvc;
    }

    [self.navigationController pushViewController:vc animated:YES];
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark - UI Events
- (void)resetAllCheckbox {

//    [_tableView enumarateTableViewCellsUsingBlock:^(UITableViewCell *cell) {
//        ProductTableViewCell *pcell = (ProductTableViewCell *)cell;
//        pcell.chkSelect.checked = NO;
//    }];
}

- (void)btnCompleteRuleTouched:(id)sender {
    [self.view endEditing:YES];

    //1.Validate Title
    RulesCreateTitleTableViewCell *tcell = (RulesCreateTitleTableViewCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]]; //마지막 섹션

    if (tcell && ![ValidateUtil validateTextfiled:tcell.txtRuleTitle type:ValidateTypeNull title:NSLocalizedString(@"이름", @"이름")]) {
        return;
    }

    if (!_tmpRuleDetail && !tcell) {
        [[JDFacade facade] alert:NSLocalizedString(@"이름을 입력하세요", @"이름을 입력하세요")];
        return;
    }

    _ruleName = !tcell ? _ruleName : tcell.txtRuleTitle.text;
    if (!_tmpRuleDetail) {//생성
        [self requestRegisterRule];

    } else {//수정
        [self requestModifyRule];
    }
}


- (IBAction)btnCancelRuleTouched:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)btnDeleteSubItemsTouched:(id)sender {
    CustomButton *btnDeleteSubItems = (CustomButton *)sender;

    ItemModel *item = (ItemModel *)btnDeleteSubItems.value;
    NSInteger section = 0;
    if ([[self triggers] containsObject:item]) {//trigger

        if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            item.predDevices = nil;
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
            item.modes = nil;
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
            item.timers = nil;
        } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우,
            item.mobileDevices = nil;
        }

    } else if ([_actions containsObject:item]) {//해당 액션을 삭제함.

        ItemModel *action = btnDeleteSubItems.value;
        action.predDevices = nil;
        action.pushes = nil;
        action.modes = nil;
        
        action.cnt = @"0";

        [_actions removeObject:item];
        section = 1;
    }

    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - MemoryWarning

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

@end
