//
//  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"


#define HEADER_TITLE_MODE       @"이 홈모드에서만"
#define HEADER_TITLE_DURATION   @"이 기간동안"
#define HEADER_TITLE_ACTION     @"이 장치가 특정 상태일 때"

#define HEADER_HEIGHT           38.0f


@implementation RulesConditionHeaderTableViewCell

@end


@implementation RulesConditionDeviceTableViewCell

@end

@implementation RulesConditionTableViewCell

@end

@implementation RulesConditionFooterTableViewCell

@end

@interface RulesConditionViewController () <UITableViewDataSource, UITableViewDelegate> {
    CustomButton *_btnModeAdd, *_btnDurationAdd;
    NSMutableArray *_arrayForHeader;
    
    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];
}

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

- (void)prepareViewDidLoad {

}


- (CGFloat)tableHeight {
    
    CGFloat height = 0;
    
    height += self.modes.count > 0 ?  HEADER_HEIGHT + 80 : 0;
    height += self.durations.count > 0 ?  HEADER_HEIGHT + 80 : 0;
    height += self.pdevices.count > 0 ?  HEADER_HEIGHT + (80 * self.pdevices.count) : 0;
//    if (_isShowingMode) {//규칙 상세일 경우,
//        height = self.modes.count > 0 ?  height + 80 + HEADER_HEIGHT + 15: height;
//        height = self.durations.count > 0 ?  height + 80 + HEADER_HEIGHT + 15: height;
//        height = self.pdevices.count > 0 ?  height + (80 * self.pdevices.count) + HEADER_HEIGHT + 15 : height;
//        
//    } else {
//        
//        height += self.modes.count > 0 ?  HEADER_HEIGHT + 80 : 0;
//        height += self.durations.count > 0 ?  HEADER_HEIGHT + 80 : 0;
//        height += self.pdevices.count > 0 ?  HEADER_HEIGHT + (80 * self.pdevices.count) : 0;
//
//    }

    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;
}


//3개의 섹션이 있을 수 있는데 하위 로우가 있는 경우만 보여줘야 한다.
-(NSInteger)getSectionCount {
    
    NSInteger sectionCount = 0;

    if ( self.modes.count > 0) sectionCount++;
    if ( self.durations.count > 0) sectionCount++;
    if ( self.pdevices.count > 0) sectionCount++;
    
    return sectionCount;
}

- (NSInteger)getRowCountFromSection:(NSInteger)sectionIdx {
    
    NSMutableArray *sections = [NSMutableArray new];
    
    if ( self.modes.count > 0) [sections addObject:self.modes];
    if ( self.durations.count > 0) [sections addObject:self.durations];
    if ( self.pdevices.count > 0) [sections addObject:self.pdevices];
    
    return [[sections objectAtIndex:sectionIdx] count];
}

- (NSString*)getHeaderTitle:(NSInteger)sectionIdx {
    
    NSMutableArray *sections = [NSMutableArray new];
    
    if ( self.modes.count > 0) [sections addObject:HEADER_TITLE_MODE];
    if ( self.durations.count > 0) [sections addObject:HEADER_TITLE_DURATION];
    if ( self.pdevices.count > 0) [sections addObject:HEADER_TITLE_ACTION];
    
    return [sections objectAtIndex:sectionIdx];
}


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

    return [self getSectionCount];
}

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

    return [self getRowCountFromSection:section];
}

- (NSString *)headerTitleForSection:(NSInteger)section {

    return [self getHeaderTitle:section];
}

//- (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 =  [self getRowCountFromSection:section] || !_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 = self.modes.count || self.durations.count || self.pdevices.count;
    return hasHeader ? HEADER_HEIGHT : CGFLOAT_MIN;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    CGFloat height = 80.0f;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = nil;
    NSString *headerTitle = [self getHeaderTitle:indexPath.section];
    
    
    SWITCH(headerTitle)
    {
        CASE(HEADER_TITLE_MODE)
        {
             cell = [self getCellModeWithTableView:tableView];
            break;
        }
        CASE(HEADER_TITLE_DURATION)
        {
            cell = [self getCellDurationWithTableView:tableView];
            break;
        }
        CASE(HEADER_TITLE_ACTION)
        {
            cell = [self getCellActionWithTableView:tableView indexPath:indexPath];
            break;
        }
    }
    
    return cell;
}

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


#pragma mark - makce row cell
//모드 로우 셀 리턴
-(UITableViewCell*)getCellModeWithTableView:(UITableView*)tableView {
    
    
    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;
    
    return tcell;
}

//기간 로우 셀 리턴
-(UITableViewCell*)getCellDurationWithTableView:(UITableView*)tableView {
    
    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_period"]];
    
    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;
    
    return tcell;
}

//동작 로우 셀 리턴
-(UITableViewCell*)getCellActionWithTableView:(UITableView*)tableView
                                    indexPath:(NSIndexPath*)indexPath {
    
    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.image = [UIImage imageNamed:[[JDFacade facade] deviceIconFromSourceSubId:subItem.sourceSubId]];
//    [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 = 40.0f;
    }
    
    tcell.bottomLine.hidden = !(indexPath.row < self.pdevices.count);

    return tcell;
}




#pragma mark - add conditions
//모드 추가
- (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.passAlreadyAdded = YES; //이미 추가 했어도 그 위에 덮어 씌움
            
            [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;
                    [deviceCondition.subItems removeAllObjects];
                    [deviceCondition.subItems addObject: snode];
                    
//                    //존재 여부 확인
//                    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 = 0;

    height += self.modes.count > 0 ?  HEADER_HEIGHT + 80 : 0;
    height += self.durations.count > 0 ?  HEADER_HEIGHT + 80 : 0;
    height += self.pdevices.count > 0 ?  HEADER_HEIGHT + (80 * self.pdevices.count) : 0;

    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
