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

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

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

#import "RegisterTimerViewController.h"
#import "PredefinedDeviceViewController.h"
#import "ScenesRegisterViewController.h"

#import "RegisterModeViewController.h"
#import "RulesTriggerOptionViewController.h"
#import "RulesRegisterViewController.h"

@implementation RulesStaticTitleTableViewCell

@end

@implementation RulesModeTableViewCell

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

@end


@interface RegisterModeViewController () <UITableViewDataSource, UITableViewDelegate, CustomRadioButtonDelegate> {
    NSMutableArray<ModeModel> *_modeList;
    CustomRadioReusableGroup *_rgroup;
    BOOL _isNotFirstLoading;
    NSInteger _sectionCount;
    RulesTriggerOptionViewController *_triggervc;
}
@end


#pragma mark - Class Definition

@implementation RegisterModeViewController


- (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 {

    if (_tmpItem.itemTypeCode) {
        ItemSubModel *subItem = _tmpItem.modes[0];
        _sectionCount = subItem.conditions && subItem.conditions.count ? 4 : 3;
    } else {
        _sectionCount = 2;
    }

    //itemSubTypeCode가 02-모드일 경우,
    [self requestModes];
}


#pragma mark - Main Logic
- (void)requestModes {
    NSString *path = API_GET_DASHBOARD_MODE_LIST;

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

        ModeListModel *fetchedModeList = (ModeListModel *)responseObject;

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

            _modeList = (NSMutableArray<ModeModel> *)[[NSMutableArray alloc] initWithArray:fetchedModeList.list];

//            for (ModeModel *mode in _tmpItem.modes) {
//                [_modeList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//
//                    ModeModel *cmode = (ModeModel *)obj;
//                    if ([mode.modeId isEqualToString:cmode.modeId]) {//동일한 모드일 경우, 저장된 모드로 교체함
//                        [_modeList replaceObjectAtIndex:idx withObject:mode];
//                        *stop = YES;
//                    }
//                }];
//            }

            for (ModeModel *mode in _tmpItem.modes) {

                NSInteger indx = [_modeList indexOfObjectPassingTest:^BOOL(ModeModel *obj, NSUInteger idx, BOOL *stop) {
                    return [mode.modeId isEqualToString:obj.modeId];
                }];

                if (indx != NSNotFound) {
                    ModeModel *tmodel = _modeList[indx];

                    [[JDFacade facade] setRadioButtonStatus:@YES object:tmodel];
//                    id radioStatus = [[JDFacade facade] getRadioButtonStatus:mode];
//                    if (radioStatus) {
//                    }
                }
            }

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

- (void)setModeContents {
    [JDFacade facade].modeList = (NSArray<ModeModel> *)[NSArray arrayWithArray:_modeList];
    [_tableView reloadData];
}


#pragma mark - UITableView DataSource & Delegate

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

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

    } else if (section == 2) {//activation cell
        count = 1;
    } else if (section == 3) {//condition cell
        count = 1;
    }

    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0) {//title
        height = _isTrigger ? 65 : 88;
    } else if (indexPath.section == 1) {//modes
        height = 100;
    } else if (indexPath.section == 2) {//activation
        height = 80.0f;
    } else if (indexPath.section == 3) {//container
        height = 240;
    }

    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {//title

        if (_isTrigger) {
            RulesStaticTitleTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"StaticTitleCellIdentifier"];

            if (tcell == nil) {
                tcell = [[RulesStaticTitleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"StaticTitleCellIdentifier"];
            }
            tcell.lblItemName.text = NSLocalizedString(@"홈모드가 바뀔 때", @"홈모드가 바뀔 때");

            cell = tcell;

        } else {
            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", 1, _modeList.count]; //모드는 무조건 1임.
            cell = tcell;
        }
    } else if (indexPath.section == 1) {
        RulesModeTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

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

        ModeModel *mode = _modeList[indexPath.row];
        [tcell.imgvItem sd_setImageWithURL:[NSURL URLWithString:mode.imageFileName] placeholderImage:nil];
        tcell.lblItemName.text = mode.modeName;

        tcell.rdoSelect.value = mode;

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

        [_rgroup addRadioButton:tcell.rdoSelect];
        cell = tcell;
    } else if (indexPath.section == 2) {//activation
        RegisterTriggerActivationTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"ActivationCellIdentifier" forIndexPath:indexPath];
        if (!tcell) {
            tcell = (RegisterTriggerActivationTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ActivationCellIdentifier"];
        }

        if (![tcell.btnTriggerOption actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnTriggerOption addTarget:self action:@selector(btnAddTriggerOptionTouched:) forControlEvents:UIControlEventTouchUpInside];
        }

        //이미지 전환
        [tcell setTriggerOptionEnable:_sectionCount == 4];
        cell = tcell;
    } else if (indexPath.section == 3) {
        RegisterContainerTableViewCell *tcell = (RegisterContainerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ContainerCellIdentifier"];

        if (!_triggervc) {//트리거뷰를 로드함.
            _triggervc = (RulesTriggerOptionViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesTriggerOptionViewController" storyboardName:@"Rules"];
            _triggervc.tmpItem = _tmpItem;

            [self addChildViewController:_triggervc];
            [_triggervc didMoveToParentViewController:self];

            if ([self isViewLoaded] && tcell.triggerOptionContainer) {
                [_triggervc beginAppearanceTransition:YES animated:NO];
                [tcell.triggerOptionContainer addSubview:_triggervc.view];
                [_triggervc endAppearanceTransition];
                [_triggervc.view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.size.mas_equalTo(tcell.triggerOptionContainer);
                    make.center.equalTo(tcell.triggerOptionContainer);
                }];
            }
        }

        cell = tcell;
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

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

    if (indexPath.section == 1) {//modes
        RulesDeviceTableViewCell *tcell = (RulesDeviceTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        [_rgroup someRadioButtonTouched:tcell.rdoSelect];
    } else if (indexPath.section == 2) {
        RegisterTriggerActivationTableViewCell *tcell = (RegisterTriggerActivationTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        [self btnAddTriggerOptionTouched:tcell.btnTriggerOption];
    }

    [_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 - RulesItemActionTableViewCellDelegate

- (IBAction)btnAddTriggerOptionTouched:(id)sender {

    _sectionCount = _sectionCount == 3 ? 4 : 3;
    [self.tableView reloadData];

    if (_sectionCount == 4) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:3];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

//- (NSMutableArray<ItemModel> *)conditions {
//    //컨디션을 설정함 - 이전 선택된 컨디션을 유지하기 위해 먼저 확인 - 테이블 뷰의 특성상.
//    NSMutableArray<ItemModel> *conditions = nil;
//    if (_triggervc && [_triggervc hasCondition]) {
//        if (!_triggervc.conditions) {
//            return nil;
//        }
//
//        conditions = _triggervc.conditions;
//    } else {
//        if (_tmpItem.timers && _tmpItem.timers.count && !_triggervc) {
//            ModeModel *mode = _tmpItem.modes[0];
//            conditions = mode.conditions;
//        }
//    }
//    return conditions;
//}

- (void)btnSelectTouched:(id)sender {

    ModeModel *mode = _rgroup.valueForChecked;

    if (_isTrigger) {//트리거일 경우,
        //컨디션을 설정함 - 이전 선택된 컨디션을 유지하기 위해 먼저 확인 - 테이블 뷰의 특성상.
        NSMutableArray<ItemModel> *conditions = nil;
        if (_triggervc && [_triggervc hasCondition]) {
            if (!_triggervc.conditions) {
                return;
            }

            conditions = _triggervc.conditions;
        } else {
            if (_tmpItem.modes && _tmpItem.modes.count && !_triggervc) {//이전에 선택된 컨디션 정보
                ModeModel *mode = _tmpItem.modes[0];
                conditions = mode.conditions;
            }
        }

        if (conditions) {
            mode.conditions = conditions;
        }

        //trigger
        _tmpItem.modes = (NSMutableArray<ModeModel> *)[[NSMutableArray alloc] initWithArray:@[mode]];

    } else {//액션일 경우,
        //actions
        _tmpItem.modes = (NSMutableArray<ModeModel> *)[[NSMutableArray alloc] initWithArray:@[mode]];

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

    [self.navigationController popViewControllerAnimated:YES];
}

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

#pragma mark - UI Events

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

@end
