//
//  RulesConditionViewController.m
//  kneet2
//
//  Created by Jason Lee on 11/25/15.
//  Copyright © 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "ItemModel.h"

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

#import "RulesConditionHomeModePopupView.h"

#import "RulesAddViewController.h"
#import "DeviceSelectPopupView.h"
#import "DeviceNodePopupView.h"
#import "UIImageView+WebCache.h"

#import "RulesConditionViewController.h"
#import "DurationPopupView.h"

@implementation RulesConditionHeaderTableViewCell

@end


@implementation RulesConditionDeviceTableViewCell

@end

@implementation RulesConditionTableViewCell

@end

@implementation RulesConditionFooterTableViewCell

@end

@interface RulesConditionViewController () <UITableViewDataSource, UITableViewDelegate> {
    CustomButton *_btnModeAdd, *_btnDurationAdd;
    NSMutableArray *_arrayForHeader, *_arrayForFooter;
    
    RulesConditionHomeModePopupView *_mpopup;
    DurationPopupView *_dpopup;
}

@property (weak, nonatomic, readonly) NSMutableArray<ItemSubModel> *modes;
@property (weak, nonatomic, readonly) NSMutableArray<ItemSubModel> *durations;
@property (weak, nonatomic, readonly) NSMutableArray<ItemSubModel> *pdevices;

@end


#pragma mark - Class Definition

@implementation RulesConditionViewController


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

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

- (void)initUI {
    [self initTableViewAsDefaultStyle:_tableView];
    _tableView.scrollEnabled = NO;
}

- (void)prepareViewDidLoad {

}


- (CGFloat)tableHeight {
    CGFloat height = _isShowingMode ? 0 : (63 * 3) + 45;
    
    if (_isShowingMode) {//규칙 상세일 경우,
        height = self.modes.count > 0 ?  height + 86 + 63 + 15: height; //add row height + header height + footer
        height = self.durations.count > 0 ?  height + 86 + 63 + 15: height;
        height = self.pdevices.count > 0 ?  height + (86 * self.pdevices.count) + 63 + 15 : height;
        
    } else {
        height = self.modes.count > 0 ?  height + 86 : height;
        height = self.durations.count > 0 ?  height + 86 : height;
        height = self.pdevices.count > 0 ?  height + (86 * self.pdevices.count) : height;
    }
    
    return height;
}

#pragma mark - Main Logic

- (NSMutableArray<ItemSubModel> *)modes {
    ItemModel *mode = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeHomeMode];
    return mode.subItems;
}

- (NSMutableArray<ItemSubModel> *)durations {
    ItemModel *duration = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeDueDate];
    return duration.subItems;
}

- (NSMutableArray<ItemSubModel> *)pdevices {
    ItemModel *pdevice = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
    return pdevice.subItems;
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSInteger count = 0;
    
    if (section == 0) {//mode
        count = self.modes.count;
    } else if (section == 1) {//duration
        count = self.durations.count;
    } else if (section == 2) {//device
        count = self.pdevices.count;
    }
    return count;
}

- (NSString *)headerTitleForSection:(NSInteger)section {
    NSString *title = nil;
    
    if (section == 0) {//mode
        title = @"이 홈모드에서만";
        
    } else if (section == 1) {//duration
        title = @"이 기간동안만";
        
    } else if (section == 2) {//devices
        title = @"이 장치가 특정 상태일 때만";
        
    }
    return title;
}

- (void)addTargetToHeaderAddButton:(CustomButton *)btnAdd section:(NSInteger)section {
    if (section == 0) {
        if (!_btnModeAdd) {
            _btnModeAdd = btnAdd;
            [btnAdd addTarget:self action:@selector(btnAddModeTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
    } else if (section == 1) {
        if (!_btnDurationAdd) {
            _btnDurationAdd = btnAdd;
            [btnAdd addTarget:self action:@selector(btnAddDurationTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
    } else if (section == 2) {
        [btnAdd addTarget:self action:@selector(btnAddDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    BOOL hasHeader = !_isShowingMode;
    if (section == 0) {//모드
        hasHeader = self.modes.count || !_isShowingMode;    //상세에서 해당 항목이 없는 경우, 표시하지 않기 위해 사용 - isShowingMode
    } else if (section == 1) {//기간
        hasHeader = self.durations.count || !_isShowingMode;
    } else if (section == 2) {//장치
        hasHeader = self.pdevices.count || !_isShowingMode;
    }
    
    UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil;
    if (!view) {
        if (hasHeader) {
            RulesConditionHeaderTableViewCell *hcell = (RulesConditionHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
            hcell.width = IPHONE_WIDTH;
            
            view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
            [view addSubview:hcell];
            
            hcell.lblTitle.text = [self headerTitleForSection:section];
            
            hcell.btnAdd.hidden = _isShowingMode;
            if (!hcell.btnAdd.hidden && ![hcell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
                [self addTargetToHeaderAddButton:hcell.btnAdd section:section];
            }
        } else {
            view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, CGFLOAT_MIN)];
        }
        
        if (_arrayForHeader.count == section) {
            [_arrayForHeader insertObject:view atIndex:section];
        }
        
    } else {
        if (hasHeader) {
            RulesConditionHeaderTableViewCell *hcell = (RulesConditionHeaderTableViewCell *)view.subviews[0];
            hcell.lblTitle.text = hcell.lblTitle.text = [self headerTitleForSection:section];
        }
    }
    
    if (!_isShowingMode) {
        [self checkHeaderButton:section];
    }
    
    return view;
}

- (void)checkHeaderButton:(NSInteger)section {
    
    if (section == 0) {//모드
        _btnModeAdd.hidden = self.modes.count > 0;
    } else if (section == 1) {//기간
        _btnDurationAdd.hidden = self.durations.count > 0;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    BOOL hasHeader = !_isShowingMode;
    CGFloat adjustHeight = 0.0f;
    
    if (section == 0) {
        hasHeader = self.modes.count || !_isShowingMode;
    } else if (section == 1) {
        hasHeader = self.durations.count || !_isShowingMode;
        adjustHeight = 0.0f;
    } else if (section == 2) {
        hasHeader = self.pdevices.count || !_isShowingMode;
        adjustHeight = 0.0f;
    }
    return hasHeader ? 63.0f + adjustHeight : CGFLOAT_MIN;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    BOOL hasFooter = !_isShowingMode;
    if (section == 0) {
        hasFooter = self.modes.count;// || !_isShowingMode;
    } else if (section == 1) {
        hasFooter = self.durations.count;// || !_isShowingMode;
    } else if (section == 2) {
        hasFooter = self.pdevices.count;// || !_isShowingMode;
    }
    
    UIView *view = _arrayForFooter.count > section ? _arrayForFooter[section] : nil;
    if (!view) {
        if (hasFooter) {
            RulesConditionFooterTableViewCell *hcell = (RulesConditionFooterTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"FooterCellIdentifier"];
            hcell.width = IPHONE_WIDTH;
            
            view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
            [view addSubview:hcell];
        } else {
            view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, CGFLOAT_MIN)];
        }
        if (_arrayForHeader.count == section) {
            [_arrayForHeader insertObject:view atIndex:section];
        }
    }
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    BOOL hasFooter = !_isShowingMode;
    if (section == 0) {
        hasFooter = self.modes.count;// || !_isShowingMode;
    } else if (section == 1) {
        hasFooter = self.durations.count;// || !_isShowingMode;
    } else if (section == 2) {
        hasFooter = self.pdevices.count;// || !_isShowingMode;
    }

    return hasFooter ? 15.0f : CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 86.0f;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    NSInteger section = indexPath.section;
    
    if (section == 0) {//mode
    
        ItemSubModel *subCondition = self.modes[0];
        
        RulesConditionTableViewCell *tcell = (RulesConditionTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"ConditionCellIdentifier"];
        
        tcell.lblItem.text = subCondition.cmdclsValueMsg;
        [tcell.imgvIcon setImage:[UIImage imageNamed:@"img_rule_icon_homemode"]];
                                  
        tcell.btnDelete.hidden = _isShowingMode;
        if (!tcell.btnDelete.hidden) {
            tcell.btnDelete.value = subCondition;
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteModeTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        tcell.bottomLine.hidden = YES;
        
        cell = tcell;
    } else if (section == 1) {//duration
     
        ItemSubModel *subCondition = self.durations[0];
        
        RulesConditionTableViewCell *tcell = (RulesConditionTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"ConditionCellIdentifier"];\
        
        NSArray *dueDates = [subCondition.cmdclsValue componentsSeparatedByString:@"~"];
        tcell.lblItem.text = [NSString stringWithFormat:@"%@ ~ %@", dueDates.firstObject, dueDates.lastObject];

        [tcell.imgvIcon setImage:[UIImage imageNamed:@"img_rule_icon_calendar"]];
        
        tcell.btnDelete.hidden = _isShowingMode;
        if (!tcell.btnDelete.hidden) {
            tcell.btnDelete.value = subCondition;
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteDurationTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        tcell.bottomLine.hidden = YES;
        
        cell = tcell;
    } else if (section == 2) {//action
        RulesConditionDeviceTableViewCell *tcell = (RulesConditionDeviceTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"DeviceCellIdentifier"];
    
        ItemSubModel *subItem = self.pdevices[indexPath.row];
        
        tcell.lblItem.text = subItem.sourceName;
        if ([subItem.deleteYn boolValue]) {//삭제된 노드가 있을 경우,
            [tcell.lblItem setStrikethrough:tcell.lblItem.text];
        }
        tcell.lblSubItem.text = subItem.sourceSubName;
        
        [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];
            }
        }
        
        if (!_isShowingMode) {
            [tcell.lblCondition setUnderLine:tcell.lblCondition.text];
        }
        
        tcell.btnDelete.hidden = _isShowingMode;
        if (!tcell.btnDelete.hidden) {
            tcell.btnDelete.value = subItem;
            if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
                [tcell.btnDelete addTarget:self action:@selector(btnDeleteDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
            }
        } else {
            tcell.constraintConditionLabelRight.constant = 15.0f;
        }
        
        tcell.bottomLine.hidden = !(indexPath.row < self.pdevices.count);

        cell = tcell;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    
    if (_isShowingMode) {
        return;
    }
    
    if (indexPath.section == 2) {//actions
        ItemSubModel *subItem = self.pdevices[indexPath.row];
        [RulesAddViewController modifyAction:subItem refDevices:_refDevices tableView:_tableView];
    }
}


#pragma mark - Table Events


- (void)btnAddModeTouched:(id)sender {
    
    ItemModel *mode = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeHomeMode];
    BOOL isNewTrigger = mode == nil;
    mode = isNewTrigger ? [[ItemModel alloc] init] : mode;
    
    if (!_mpopup) {
        _mpopup = [[RulesConditionHomeModePopupView alloc] initFromNib];
    }
    
    _mpopup.condition = mode;
    [_mpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            if (isNewTrigger) {
                [_conditions addObject:mode];
            }

            [self updateTableView];
        }
    }];
}

- (void)btnAddDurationTouched:(id)sender {
    
    ItemModel *dueDate = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeDueDate];
    BOOL isNewTrigger = dueDate == nil;
    dueDate = isNewTrigger ? [[ItemModel alloc] init] : dueDate;
    
    if (!_dpopup) {
        _dpopup = [[DurationPopupView alloc] initFromNib];
    }
    
    _dpopup.condition = dueDate;
    [_dpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            if (isNewTrigger) {
                [_conditions addObject:dueDate];
            }
            
            [self updateTableView];
        }
    }];
}

- (void)btnAddDeviceTouched:(id)sender {
    
    ItemModel *deviceCondition = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
    BOOL isNewTrigger = deviceCondition == nil;
    deviceCondition = isNewTrigger ? [[ItemModel alloc] init] : deviceCondition;
    
    DeviceSelectPopupView *dpopup = [[DeviceSelectPopupView alloc] initFromNib];
    dpopup.refDevices = _refDevices;
    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 (isNewTrigger) {
                        deviceCondition.itemName = @"이 장치가 특정 상태일 때만";
                        deviceCondition.itemSubTypeCode = ksItemSubTypeCodeDevice; //트리거 타입 설정
                        
                        deviceCondition.subItems = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];
                        
                        [_conditions addObject:deviceCondition];
                    }
                    
                    ItemSubModel *snode = npopup.selectedNode;
                    //존재 여부 확인
                    if (![deviceCondition.subItems objectByUsingPredicateFormat:@"sourceId == %@ && sourceSubId == %@", snode.sourceId, snode.sourceSubId]) {
                        [deviceCondition.subItems addObject: snode];
                    }
                    
                    [self updateTableView];
                }
            }];
        }
    }];
}

- (void)btnDeleteModeTouched:(id)sender {
    CustomButton *btnDelete = (CustomButton *)sender;
    ItemSubModel *mode = btnDelete.value;
    
    [self.modes removeObject:mode];
    
    [self updateTableView];
}

- (void)btnDeleteDurationTouched:(id)sender {
    
    CustomButton *btnDelete = (CustomButton *)sender;
    ItemSubModel *dueDate = btnDelete.value;
    
    [self.durations removeObject:dueDate];
    
    [self updateTableView];
}

- (void)btnDeleteDeviceTouched:(id)sender {
    
    CustomButton *btnDelete = (CustomButton *)sender;
    ItemSubModel *pdevice = btnDelete.value;

    //선택 설정을 초기화
    [[JDFacade facade] setRadioButtonStatus:@NO object:pdevice];
    
    for (CmdClsValueModel *cmdclsValue in pdevice.cmdclsValueList) {
        cmdclsValue.isSelected = NO;
    }
    [self.pdevices removeObject:pdevice];
    
    [self updateTableView];
}

- (void)updateTableView {
    
    CGFloat height = (63 * 3) + 45;
    
    height = self.modes.count > 0 ?  height + 86 : height;
    height = self.durations.count > 0 ?  height + 86 : height;
    height = self.pdevices.count > 0 ?  height + (86 * self.pdevices.count) : height;
    
    self.view.height = height;
    
    [_tableView reloadData];
    
    if ([self.parentViewController isKindOfClass:[RulesAddViewController class]]) {
        RulesAddViewController *rvc = (RulesAddViewController *)self.parentViewController;
        [rvc.tableView reloadData];
    }
}

#pragma mark - UI Events


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

@end