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

#import "RequestHandler.h"

#import "ModeModel.h"
#import "SceneModel.h"
#import "ItemModel.h"

#import "CustomTableView.h"
#import "CustomImageView.h"
#import "CustomLabel.h"
#import "CustomButton.h"
#import "UIImageView+WebCache.h"

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

#import "HomeModeSettingsViewController.h"

@implementation HomeSettingsTitleTableViewCell

@end

@implementation HomeSettingsDeviceTableViewCell

@end

@implementation HomeSettingsAppendTableViewCell

@end

@interface HomeModeSettingsViewController () {
    
    NSMutableArray<ItemModel> *_items;
    NSMutableArray<ItemSubModel> *_subItems;
}
@end


#pragma mark - Class Definition

@implementation HomeModeSettingsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [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 성공 ,
            _items = fetchedItemList.list;
        }
        
        [self requestSceneDetailsByHomeMode];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

//현재 모드에 설정된 액션 리스트를 조회함
- (void)requestSceneDetailsByHomeMode {
    
    NSString *path = [NSString stringWithFormat:API_GET_SCENE_DETAIL_HOMEMODE, _mode.modeId];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[ItemSubListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        ItemSubListModel *fetchedSubItems = (ItemSubListModel *) responseObject;
        
        if (fetchedSubItems && fetchedSubItems.list && fetchedSubItems.list.count) {//API 성공 ,
            _subItems = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:fetchedSubItems.list];
        }
        
        [self matchItemListWithSubItemsForMode];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

//장치리스트와 현재 모드설정을 매칭함.
- (void)matchItemListWithSubItemsForMode {
    
    for (ItemSubModel *subItem in _subItems) {//scene detail
    
        //모드에 설정된 디바이스와 장치 리스트의 매칭 및 커맨드 클래스 밸루 설정
        NSString *filter = @"sourceId == %@ && sourceSubId == %@";
        NSArray *matchedSubitems = [_items matchedArrayInSubArrays:@"subItems" predicateFormat:filter, subItem.sourceId, subItem.sourceSubId];
        
        for (ItemSubModel *pSubItem in matchedSubitems) {
            [[JDFacade facade] setRadioButtonStatus:@YES object:pSubItem]; //해당 노드를 선택 표시
            
            NSString *vfilter = @"cmdclsValue == %@";
            NSArray *matchedValues = [pSubItem.cmdclsValueList filteredArrayUsingPredicateFormat:vfilter, subItem.cmdclsValue];
            
            if (matchedValues && matchedValues.count) {//설정 초기화
                CmdClsValueModel *cmdclsValue = matchedValues[0];
                [[JDFacade facade] setRadioButtonStatus:@YES object:cmdclsValue];
                cmdclsValue.isSelected = YES;
            }
        }
    }
    
    [_tableView reloadData];
}

- (void)requestRegisterModeAction:(NSArray *)subItems {
    //parameters
    NSDictionary *parameter = @{@"item_sub": subItems};
    
    NSString *path = [NSString stringWithFormat:API_POST_SCENE_HOMEMODE, _mode.modeId];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[SceneModel class] completion:^(id responseObject) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            [[JDFacade facade] toast:NSLocalizedString(@"홈모드 설정을 저장했습니다", @"홈모드 설정을 저장했습니다")];
        }];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 1;
    
    if (section == 1) {
        NSArray *matchedSubItems = [_items matchedArrayInSubArrays:@"subItems" objectName:ksCustomRadioButtonStatus condition:YES];
        count = matchedSubItems && matchedSubItems.count ? matchedSubItems.count : 0;
    }
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    
    if (indexPath.section == 0) {
        height = 101.0f;
    } else if (indexPath.section == 1 || indexPath.section == 2) {
        height = 86.0f;
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    NSInteger section = indexPath.section;
    
    if (section == 0) {
        HomeSettingsTitleTableViewCell *tcell = (HomeSettingsTitleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        [tcell.imgvMode sd_setImageWithURL:[NSURL URLWithString:_mode.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
        tcell.lblModeTitle.text = _mode.modeName;
        
        cell = tcell;
    } else if (section == 1) {
        
        //노드 액션이 선택된 노드만 출력함.
        NSInteger fcount = indexPath.row; //선택된 액션만 찾기 위한 인덱스
        NSArray *matchedSubItems = [_items matchedArrayInSubArrays:@"subItems" objectName:ksCustomRadioButtonStatus condition:YES];
        
        ItemSubModel *subItem = nil;
        for (subItem in matchedSubItems) {
            if (fcount == 0) {
                break;
            } else {
                fcount--;
            }
        }
        
        HomeSettingsDeviceTableViewCell *tcell = (HomeSettingsDeviceTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DeviceCellIdentifier"];
        [tcell.imgvDevice sd_setImageWithURL:[NSURL URLWithString:subItem.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
        tcell.lblDeviceName.text = subItem.sourceName;
        tcell.lblNodeName.text = subItem.sourceSubName;

        //노드의 액션 값을 세팅함.
        if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
            CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
            tcell.lblActionName.text = cmdclsValue.cmdclsValueMsg;
        } else {
            tcell.lblActionName.text = subItem.cmdclsValueMsg;
        }
        
        if (![tcell.lblActionName.text isEmptyString]) {
            [tcell.lblActionName setUnderLine:tcell.lblActionName.text];
        }
        
        tcell.lblActionName.value = subItem;
//        [tcell.lblActionName setUnderLine:tcell.lblActionName.text];
        
        if (!tcell.lblActionName.touchHandler) {
            [tcell.lblActionName addTouchEventHandler:^(id label) {
                [self lblActionNameTouched:label];
            }];
        }
        
        tcell.btnDelete.value = subItem;
        if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnDelete addTarget:self action:@selector(btnDeleteDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    } else if (section == 2) {
        HomeSettingsAppendTableViewCell *tcell = (HomeSettingsAppendTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"AppendCellIdentifier"];
        
        if (![tcell.btnAppend actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnAppend addTarget:self action:@selector(btnAppendTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    
    if (indexPath.section == 1) {
        HomeSettingsDeviceTableViewCell *tcell = (HomeSettingsDeviceTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        ItemSubModel *subItem = tcell.lblActionName.value;
        
        [self modifyAction:subItem];
    }
}

- (void)btnDeleteDeviceTouched:(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;
    }
    
    [_tableView reloadData];
}

//장치 선택
- (void)btnAppendTouched:(id)sender {
    
    DeviceSelectPopupView *popup = [[DeviceSelectPopupView alloc] initFromNib];
    popup.refDevices = _items;
    popup.typeCode = ksItemTypeCodeTrigger;
    
    [popup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//ok
            DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
            npopup.refDevice = popup.selectedDevices[0];
            npopup.typeCode = ksItemTypeCodeTrigger;
            
            [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 0) {//OK
                    [_tableView reloadData];
                }
            }];
        }
    }];
}

- (void)modifyAction:(ItemSubModel *)subItem {
    
    ItemModel *item = [_items objectKey:@"sourceId" eqaulToString:subItem.sourceId];
    
    //노드 선택 팝럽.
    DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
    npopup.refDevice = item;
    npopup.typeCode = ksItemTypeCodeTrigger; 
    npopup.isModifyMode = YES;
    
    [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [_tableView reloadData];
        }
    }];
}

- (void)lblActionNameTouched:(id)sender {
    CustomLabel *label = (CustomLabel *)sender;
    ItemSubModel *subItem = label.value;
    
    [self modifyAction:subItem];
}

#pragma mark - UI Events
- (IBAction)btnCompleteTouched:(id)sender {
    
    //선택된 노드만 출력함.
    NSMutableArray *pSubItems = [[NSMutableArray alloc] init];
    
    NSArray *matchedSubItems = [_items matchedArrayInSubArrays:@"subItems" objectName:ksCustomRadioButtonStatus condition:YES];
    for (ItemSubModel *pSubItem in matchedSubItems) {
        CmdClsValueModel *pCmdClsValue = [pSubItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
        
        NSDictionary *dSubITem = @{@"source_id": pSubItem.sourceId,
                                   @"source_sub_id": pSubItem.sourceSubId,
                                   @"cmdcls_value": pCmdClsValue.cmdclsValue};
        
        [pSubItems addObject:dSubITem];
    }

    if (!pSubItems.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"실행할 장치를 선택하세요", @"실행할 장치를 선택하세요")];
        return;
    }

    [self requestRegisterModeAction:pSubItems];
}

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


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


@end