//
//  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 "CustomLabel.h"
#import "CustomButton.h"
#import "CustomImageView.h"
#import "CustomTableView.h"

#import "UIImageView+WebCache.h"

#import "RulesAddViewController.h"
#import "CustomCheckBox.h"
#import "DeviceSelectPopupView.h"
#import "DeviceNodePopupView.h"
#import "TriggerSelectPopupView.h"
#import "DeviceModel.h"
#import "CustomTextView.h"

@implementation RulesAddHeaderTableViewCell

@end

@implementation RulesAddTableViewCell

@end


@implementation RulesAddPushTableViewCell


@end

@implementation RulesAddConditionHeaderTableViewCell


@end

@implementation RulesAddConditionTableViewCell


@end

@implementation RulesAddFooterTableViewCell

@end

@interface RulesAddViewController () <CustomTextViewDelegate> {
    NSMutableArray<ItemModel> *_triggers, *_actions, *_conditions, *_pushes;
    NSMutableArray<ItemModel> *_triggerDevices, *_actionDevices;
    
    BOOL _isNotFirstLoading, _isCustomCreation;
    NSMutableArray *_arrayForHeader, *_arrayForFooter;
    
    CustomButton *_btnTriggerAdd, *_btnPushAdd;
    
    CustomCheckBox *_chkConditions;
}
@end


#pragma mark - Class Definition

@implementation RulesAddViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    _arrayForHeader = [[NSMutableArray alloc] init];
    _arrayForFooter = [[NSMutableArray alloc] init];
    
    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    [self initTableViewAsDefaultStyle:_tableView];
}

- (void)prepareViewDidLoad {
    [self requestDeviceListForHome];
}

#pragma mark - Main Logic

- (void)requestDeviceListForHome {
    //parameters
    NSDictionary *parameter = @{@"item_type_code": ksItemTypeCodeAction};
    
    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 성공 ,
            _triggerDevices = fetchedItemList.list;
            _actionDevices = [(NSMutableArray<ItemModel> *)[NSMutableArray alloc] initWithArray:_triggerDevices copyItems:YES];
        }
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger count = 0;
    if (section == 0) {//triggers
        count = _triggers && _triggers.count ? _triggers.count : 0;
        
    } else if (section == 1) {//actions
        
        NSArray *matchedSubItems = [_actions matchedArrayInSubArrays:@"subItems" objectName:ksCustomRadioButtonStatus condition:YES];
        count = matchedSubItems && matchedSubItems.count ? matchedSubItems.count : 0;
        
    } else if (section == 2) {//push-message
        count = _pushes && _pushes.count ? _pushes.count : 0;
        
    } else if (section == 3) {//conditions
        count = _chkConditions.checked ? 1 : 0;
    }
    
    return count;
}

- (NSString *)headerTitleForSection:(NSInteger)section {
    NSString *title = nil;
    
    if (section == 0) {//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:ksItemSubTypeCodeSun]) {
                title = @"해뜰때 / 질때";
            }
        }
        
    } else if (section == 1) {//action
        title = @"이 장치를 실행";
//        title = _actions && _actions.count ? @"선택됨" : title;
    } else if (section == 2) {//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 == 0) {
        _btnTriggerAdd = btnAdd;
        [btnAdd addTarget:self action:@selector(btnAddTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
        
    } else if (section == 1) {
        [btnAdd addTarget:self action:@selector(btnAddActionTouched:) forControlEvents:UIControlEventTouchUpInside];
        
    } else if (section == 2) {
        _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 || section == 1 || section == 2) {//TODO : hide add button or not;

            RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
            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 == 3) {
            RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ConditionHeaderCellIdentifier"];
            
            view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
            [view addSubview:hcell];
        }
        
        if (_arrayForHeader.count == section) {
            [_arrayForHeader insertObject:view atIndex:section];
        }
    } else {
        
         if (section == 0 || section == 1 || section == 2) {
             RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)view.subviews[0];
             hcell.lblTitle.text = hcell.lblTitle.text = [self headerTitleForSection:section];
             
         } else if (section == 3) {
             RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)view.subviews[0];
         }
    }
    
    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 90.0f;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *view = _arrayForFooter.count > section ? _arrayForFooter[section] : nil;
    if (!view) {
        
        RulesAddFooterTableViewCell *hcell = (RulesAddFooterTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"FooterCellIdentifier"];
        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 {
    return 15.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0.0f;
    NSInteger section = indexPath.section;
    
    if (section == 0) {//triggers
        height = 95;
        
    } else if (section == 1) {//actions
        height = 95;
        
    } else if (section == 2) {//push-message
        height = 115;
        
    } else if (section == 3) {//conditions
        height = 255;
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    
    UITableViewCell *cell = nil;
    
    if (section == 0) {//triggers
        ItemModel *item = _triggers[indexPath.row];
        ItemSubModel *subItem = [item.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
        
        RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
        tcell.lblItem.text = item.sourceName;
        tcell.lblSubItem.text = subItem.sourceSubName;
        
        //노드의 액션 값을 세팅함.
        if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
            CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
            tcell.lblCondition.text = [DeviceModel contentValueMsgByCmdClsCode:subItem.cmdclsCode cmdclsTypeId:(NSString *)subItem.cmdclsTypeId contentValue:cmdclsValue.cmdclsValue];
        } else {
            tcell.lblCondition.text = subItem.cmdclsValueMsg;
        }
        
        [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:subItem.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
        
        if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    } else if (section == 1) {//actions
        
        ItemModel *item = _actions[indexPath.row];

        //노드 액션이 선택된 노드만 출력함.
        NSInteger fcount = indexPath.row; //선택된 액션만 찾기 위한 인덱스
        NSArray *matchedSubItems = [_actions matchedArrayInSubArrays:@"subItems" objectName:ksCustomRadioButtonStatus condition:YES];
        
        ItemSubModel *subItem = nil;
        for (subItem in matchedSubItems) {
            if (fcount == 0) {
                break;
            } else {
                fcount--;
            }
        }
        
        RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
        tcell.lblItem.text = item.sourceName;
        [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:item.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 {
            tcell.lblCondition.text = subItem.cmdclsValueMsg;
        }
        
        tcell.btnDelete.value = subItem;
        
        if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteActionTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
        
    } else if (section == 2) {//push-message
        RulesAddPushTableViewCell *tcell = (RulesAddPushTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"PushCellIdentifier"];
        tcell.txvMessage.delegate = self;
        
        cell = tcell;

    } else if (section == 3) {//conditions
        RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"ConditionCellIdentifier"];
        
        cell = tcell;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - TableView UI Events


- (void)btnAddTriggerTouched:(id)sender {
    if (!_triggers) {
        _triggers = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
    }
    
    TriggerSelectPopupView *tpopup = [[TriggerSelectPopupView alloc] initFromNib];
    tpopup.refTriggers = _triggers;
    tpopup.refDevices = _triggerDevices;
    [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
                    if (!_actions) {
                        _actions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
                    }
                    
                    [_actions addObject:npopup.refDevice];
                    [_tableView reloadData];
                }
            }];
        }
    }];
}

- (void)btnAddPushMessageTouched:(id)sender {
    if (!_pushes) {
        _pushes = [(NSMutableArray<ItemModel> *)[NSMutableArray alloc] init];
    }
    
    if (!_pushes.count) {
        ItemModel *push = [[ItemModel alloc] init];
        push.itemSubTypeCode = ksItemSubTypeCodeAppPush;
        
        [_pushes addObject:push];
    }
    
    [_tableView reloadData];
}


- (void)btnDeleteTriggerTouched:(id)sender {
    if (_triggers && _triggers.count) {
        [_triggers removeAllObjects];
    }
    
    [_tableView reloadData];
}

- (void)btnDeleteActionTouched:(id)sender {
    CustomButton *btnDelete = (CustomButton *)sender;
    
    ItemSubModel *subItem = (ItemSubModel *)btnDelete.value;
    
    //선택 설정을 초기화
    [[JDFacade facade] setRadioButtonStatus:@NO object:subItem];
    
    for (CmdClsValueModel *cmdclsValue in subItem.cmdclsValueList) {
        cmdclsValue.isSelected = NO;
    }
    
    //액션과 일치하는 서브아이템을 삭제해줌.
    [_actions enumerateObjectsUsingBlock:^(ItemModel *action, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *matchedArray = [action.subItems matchedArrayByObjectName:ksCustomRadioButtonStatus condition:YES];
        
        if (!matchedArray.count) {
            [_actions removeObject:action];
        }
    }];
    
    [_tableView reloadData];
}

#pragma mark - CustomTextView Delegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    _btnPushAdd.hidden = textView.text.length > 0;

    NSLog(@"%s\n %zd", __PRETTY_FUNCTION__, textView.text.length);
    
    return textView.text.length < 120;
}

#pragma mark - UI Events


- (IBAction)btnConfirmTouched:(id)sender {
    //validate

}

- (IBAction)btnCancelTouched:(id)sender {
    [[JDFacade facade] dismissModalStack:YES completion:nil];
}

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




@end