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

#import "RequestHandler.h"
#import "RuleModel.h"
#import "ModeModel.h"

#import "CustomLabel.h"
#import "CustomRadioGroup.h"
#import "CustomImageView.h"
#import "UIImageView+WebCache.h"

#import "PredefinedDeviceViewController.h"
#import "CustomCheckBox.h"
#import "CustomButton.h"
#import "ScenesRegisterViewController.h"
#import "CommandClassControlView.h"
#import "RulesRegisterViewController.h"
#import "NoContentView.h"

@implementation RulesDeviceTitleViewCell

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

@end

@implementation RulesDeviceTableViewCell

- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;

    self.backgroundColor = [UIColor clearColor];
}

@end


@interface PredefinedDeviceViewController () <UITableViewDataSource, UITableViewDelegate, CustomRadioButtonDelegate, CustomCheckBoxDelegate> {

    NSMutableArray<PredefinedDeviceModel> *_preDeviceList;

    NSInteger _triggerCount, _actionCount, _conditionCount;
    NSString *_typeCode;
    BOOL _isNotFirstLoading;

    CustomRadioReusableGroup *_rgroup;
}
@end


#pragma mark - Class Definition

@implementation PredefinedDeviceViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    // initialize
    _rgroup = [[CustomRadioReusableGroup alloc] init];
    _rgroup.tableView = _tableView;

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    
    

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

    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.separatorColor = kUILineColor2;
    _tableView.backgroundColor = [UIColor clearColor];

    _tableView.tableFooterView = [[UIView alloc] init]; //this call table events;
    
    //Localization
    [_btnSelect setTitle:NSLocalizedString(@"선택", @"선택") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {

    //itemSubTypeCode가 01-디바이스일 경우,
//    if (_predRuleId && ![_predRuleId isEmptyString]) {
//        _typeCode = _tmpItem.itemTypeCode;
//
//    }  else if (_predSceneId && ![_predSceneId isEmptyString]) {
//        _typeCode = @"02";
//    }

    _typeCode = @"02";
    [self requestPredefinedDevices];
}



#pragma mark - Main Logic
- (void)requestPredefinedDevices {

    NSString *path = nil;
    if (_predRuleId && ![_predRuleId isEmptyString]) {
        path = [NSString stringWithFormat:API_GET_PRERULE_DEVICES, _tmpItem.predRuleId, _tmpItem.predItemSequence];

    }  else if (_predSceneId && ![_predSceneId isEmptyString]) {
        path = [NSString stringWithFormat:API_GET_PRESCENE_DEVICES, _tmpItem.predSceneId, _tmpItem.predActionSequence];

    }

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

        PredefinedDeviceListModel *fetchedPreDeviceList = (PredefinedDeviceListModel *)responseObject;

        if (fetchedPreDeviceList && fetchedPreDeviceList.list && fetchedPreDeviceList.list.count) {//API 성공 ,

            _preDeviceList = (NSMutableArray<PredefinedDeviceModel> *)[[NSMutableArray alloc] initWithArray:fetchedPreDeviceList.list];

            for (PredefinedDeviceModel *pdevice in _tmpItem.predDevices) {//이전에 선택된 디바이스와 사전정의 장치 목록을 매칭시킴.

                NSInteger indx = [_preDeviceList indexOfObjectPassingTest:^BOOL(PredefinedDeviceModel *obj, NSUInteger idx, BOOL *stop) {
                    return [pdevice.deviceId isEqualToString:obj.deviceId] && [pdevice.nodeId isEqualToString:obj.nodeId];
                }];

                if (indx != NSNotFound) {
                    PredefinedDeviceModel *tdevice = _preDeviceList[indx];

                    tdevice.cmdclsValue = pdevice.cmdclsValue;
                    tdevice.enable = YES;
//                    id checkStatus = [[JDFacade facade] getCheckBoxStatus:pdevice];
//                    id radioStatus = [[JDFacade facade] getRadioButtonStatus:pdevice];

                    [[JDFacade facade] setRadioButtonStatus:@YES object:tdevice];  //for radio box
                    [[JDFacade facade] setCheckBoxStatus:@YES object:tdevice];  //for radio box
                    
//                    if (checkStatus) {
//                        [[JDFacade facade] setCheckBoxStatus:checkStatus object:tdevice];  //for radio box
//                    }
//
//                    if (radioStatus) {
//                        [[JDFacade facade] setRadioButtonStatus:radioStatus object:tdevice];  //for radio box
//                    }
//                    [_preDeviceList replaceObjectAtIndex:indx withObject:pdevice];
                }
            }

            [self setPredefinedDeviceContents];
        } else {
            NoContentView *noContentView = [NoContentView viewFromNib];
            CGRect nr = noContentView.frame;
            nr.size.height = _tableView.frame.size.width;
            noContentView.frame = nr;

            _tableView.tableFooterView = noContentView;
            _tableView.scrollEnabled = NO;
        }

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

- (void)setPredefinedDeviceContents {
    [_tableView reloadData];
}

#pragma mark - UITableView DataSource & Delegate

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 0;
    if (section == 0) {
        count = 1;
    } else if (section == 1) {
        count = _preDeviceList && _preDeviceList.count ? _preDeviceList.count : 0;
    }

    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0) {//title
        height = 88;
    } else if (indexPath.section == 1) {//devices
        PredefinedDeviceModel *pdevice = _preDeviceList[indexPath.row];
        height = (!pdevice.predCmdclsValue || [pdevice.predCmdclsValue isEmptyString]) ? 132.0f : 100.0f; //컨트롤을 로드 - 커맨드클래스 밸루 리스트가 있는 장치에 한함.
    }

    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {//title
        RulesDeviceTitleViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];

        if (tcell == nil) {
            tcell = [[RulesDeviceTitleViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TitleCellIdentifier"];
        }
        [tcell.btnActionTitle setTitle:_tmpItem.itemName forState:UIControlStateNormal];
        tcell.lblSelectCount.text = [NSString stringWithFormat:@"%zd / %zd", [self countForCheckedActions], _preDeviceList.count];

        cell = tcell;

    } else if (indexPath.section == 1) {//predefined device list
        RulesDeviceTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

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

        PredefinedDeviceModel *pdevice = _preDeviceList[indexPath.row];
        [tcell.imgvItem sd_setImageWithURL:[NSURL URLWithString:pdevice.imageFileName] placeholderImage:nil];
        tcell.lblItemName.text = pdevice.deviceName;
        tcell.lblSubItems.text = pdevice.nodeName;

        if ([_typeCode isEqualToString:ksItemTypeCodeTrigger] || [_typeCode isEqualToString:ksItemTypeCodeCondition]) {//트리거 또는 컨디션
            tcell.chkSelect.hidden = YES;

            tcell.rdoSelect.value = pdevice;
            if (indexPath.row == 0 && !_isNotFirstLoading && !_tmpItem.predDevices) {
                _isNotFirstLoading = YES;
                tcell.rdoSelect.checked = YES;
            } else {
                tcell.rdoSelect.checked = [tcell.rdoSelect getRadioStatusFromValue];
            }

            [_rgroup addRadioButton:tcell.rdoSelect];

        } else if ([_typeCode isEqualToString:ksItemTypeCodeAction]) {//액션
            tcell.rdoSelect.hidden = YES;

            tcell.chkSelect.delegate = self;
            tcell.chkSelect.value = pdevice;
            tcell.chkSelect.checked = [tcell.chkSelect getCheckStatusFromValue];
        }

        //뷰를 초기화함.
        [[tcell.controlContainerView subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            UIView *subview = (UIView *)obj;
            [subview removeFromSuperview];
        }];

        if (!pdevice.predCmdclsValue || [pdevice.predCmdclsValue isEmptyString]) {//컨트롤을 로드 - 커맨드클래스 밸루 리스트가 있는 장치에 한함.

            CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:pdevice.cmdclsType];
            controlView.device = pdevice;
            controlView.enable = pdevice.enable;
            controlView.isConditionMode = YES;

            tcell.controlContainerView.hidden = !controlView;
            if (!tcell.controlContainerView.hidden) {
                UIView *superview = tcell.controlContainerView;
                [superview addSubview:controlView];

                [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(superview.mas_top);
                    make.left.equalTo(superview.mas_left);
                    make.center.equalTo(superview);
                }];
            }
        }

        cell = tcell;
    }
    return cell;
}

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

    if (indexPath.section == 0) //제목 셀인 경우, 리턴
        return;

    PredefinedDeviceModel *pdevice = _preDeviceList[indexPath.row];
    RulesDeviceTableViewCell *tcell = (RulesDeviceTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];

    if ([_typeCode isEqualToString:ksItemTypeCodeTrigger] || [_typeCode isEqualToString:
                                                              ksItemTypeCodeCondition]) {//트리거 또는 컨디션
        tcell.rdoSelect.value = pdevice;
        tcell.rdoSelect.checked = !tcell.rdoSelect.checked;

        [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } else if ([_typeCode isEqualToString:ksItemTypeCodeAction]) {//액션일 경우,

        [tcell.chkSelect checkBoxClicked];
    }

    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}


- (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 - CustomCheckBox Delegate
- (void)didCheckBoxClicked:(id)sender {
    CustomCheckBox *chk = (CustomCheckBox *)sender;
    PredefinedDeviceModel *pdevice = chk.value;

    if (!pdevice.predCmdclsValue || [pdevice.predCmdclsValue isEmptyString]) {//컨트롤을 로드 - 커맨드클래스 밸루 리스트가 있는 장치에 한함.
        pdevice.enable = chk.checked;
    }

    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - UI Events
- (NSInteger)countForCheckedActions {
    NSInteger count = 0;
    for (PredefinedDeviceModel *pdevice  in _preDeviceList) {
        if ([[[JDFacade facade] getCheckBoxStatus:pdevice] boolValue]) {
            count++;
        }
    }
    return count;
}

- (void)btnSelectTouched:(id)sender {

    if ([_typeCode isEqualToString:ksItemTypeCodeTrigger] || [_typeCode isEqualToString:ksItemTypeCodeCondition]) {//디바이스 1건

        PredefinedDeviceModel *predDevice = _rgroup.valueForChecked;
        _tmpItem.predDevices = (NSMutableArray<PredefinedDeviceModel> *)[[NSMutableArray alloc] initWithArray:@[predDevice]];

    } else if ([_typeCode isEqualToString:ksItemTypeCodeAction]) {//디바이스 멀티

        _tmpItem.predDevices = (NSMutableArray<PredefinedDeviceModel> *)[[NSMutableArray alloc] init];

        for (PredefinedDeviceModel *pdevice  in _preDeviceList) {
            if ([[[JDFacade facade] getCheckBoxStatus:pdevice] boolValue]) {
                [_tmpItem.predDevices addObject:pdevice];
            }
        }

        if (!_tmpItem.predDevices.count) {
            [[JDFacade facade] alert:NSLocalizedString(@"선택된 항목이 없습니다", @"선택된 항목이 없습니다")];
            return;
        }
    }

    if (_isCustomCreation) {//자유 선택
        if (_tmpItem.predSceneId && ![_tmpItem.predSceneId isEmptyString]) {//씬일 경우,

            ScenesRegisterViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ScenesRegisterViewController class]];
            [vc addItem:_tmpItem];

        } else if (_tmpItem.predRuleId && ![_tmpItem.predRuleId isEmptyString]) {//룰일 경우,
            RulesRegisterViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[RulesRegisterViewController class]];
            [vc addItem:_tmpItem];
        }
    }

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

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

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

@end
