//
//  RegisterCmdClsViewController.m
//  kneet
//
//  Created by Jason Lee on 5/22/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "RequestHandler.h"
#import "RuleModel.h"
#import "DeviceModel.h"

#import "CustomLabel.h"
#import "CustomImageView.h"
#import "UIButton+WebCache.h"

#import "CustomButton.h"

#import "RulesTriggerOptionViewController.h"

#import "RegisterCmdClsViewController.h"
#import "RegisterModeViewController.h"
#import "RegisterTimerViewController.h"
#import "CommandClassListPopupView.h"

//tableview
@interface RegisterCmdClsTableViewCell () {

}
@end

@implementation RegisterCmdClsTableViewCell
- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.collectionView.scrollEnabled = NO;
}

- (void)setCollectionViewDataSourceDelegate:(id<UICollectionViewDataSource, UICollectionViewDelegate>)dataSourceDelegate indexPath:(NSIndexPath *)indexPath
{
    self.collectionView.dataSource = dataSourceDelegate;
    self.collectionView.delegate = dataSourceDelegate;
    self.collectionView.indexPath = indexPath;

    [self.collectionView reloadData];
}
@end

@interface RegisterCmdClsCollectionView () {

}

@end
@implementation RegisterCmdClsCollectionView

@end

//CollectionViewCell
@interface RegisterCmdClsCollectionViewCell () {
    UIImage *_btnBgImageNormal, *_btnBgImageHighlight;
}
@end

@implementation RegisterCmdClsCollectionViewCell

- (void)setBtnItemImage:(BOOL)isActive {
    if (isActive) {
        [_btnItem setBackgroundImage:_btnBgImageHighlight forState:UIControlStateNormal];
    } else {
        [_btnItem setBackgroundImage:_btnBgImageNormal forState:UIControlStateNormal];
    }
}

- (void)awakeFromNib {
    _btnBgImageNormal = [UIImage imageNamed:@"tp_01_img_rule_triggericon_bg"];
    _btnBgImageHighlight = [UIImage imageNamed:@"tp_01_img_rule_triggericon_bg_active"];
}

@end

//viewController
@interface RegisterCmdClsViewController () <UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>  {
    NSMutableArray<ItemModel> *_itemList;

    BOOL _isNotFirstLoading;
    NSInteger _sectionCount;
    RulesTriggerOptionViewController *_triggervc;
    ItemModel *_currentItem;
}
@end


#pragma mark - Class Definition

@implementation RegisterCmdClsViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    
    

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

    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];

    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {//iOS 7인 경우, Seperate 설정
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    _tableView.tableFooterView = [[UIView alloc] init];
    
    //Localization
    [_btnSelect setTitle:NSLocalizedString(@"선택", @"선택") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {
    ItemSubModel *subItem = _tmpItem.predDevices && _tmpItem.predDevices.count ? _tmpItem.predDevices[0] : nil;
    _sectionCount = subItem.conditions && subItem.conditions.count ? 4 : 3;

    [self requestRuelsCommandClassList];
}

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

    NSString *path = [NSString stringWithFormat:API_GET_RULE_CMDCLS, _tmpItem.itemTypeCode];

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

        ItemListModel *result = (ItemListModel *)responseObject;

        if (result) {//API 성공 ,
            _itemList = (NSMutableArray<ItemModel> *)[NSMutableArray arrayWithArray:result.list];
            [self matchActionsForCommnadClassList];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)matchActionsForCommnadClassList {
    //이전에 선택된 액션과 액션리스트를 매칭시킴.
    NSInteger index = [_itemList indexOfObjectPassingTest:^BOOL(ItemModel *cmdcls, NSUInteger idx, BOOL *stop) {
        return [_tmpItem.predItemSequence isEqualToString:cmdcls.predItemSequence];
    }];

    if (index != NSNotFound) {
        if (_tmpItem.predDevices) {
            ItemModel *cmdcls = _itemList[index];
            cmdcls.predDevices = _tmpItem.predDevices;
            _currentItem = cmdcls;
        }
    }

    [_tableView reloadData];
}


#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _itemList.count ? _sectionCount : 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 1;
    return count;
}

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

    CGFloat height = 0;
    if (indexPath.section == 0) {//title
        height = 65.0f;
    } else if (indexPath.section == 1) {//collection cells
        RegisterCmdClsTableViewCell *cell = (RegisterCmdClsTableViewCell *)[self tableView:_tableView cellForRowAtIndexPath:indexPath];
        cell.collectionView.delegate = self;
        cell.collectionView.dataSource = self;

        CGFloat adjustHeight = 0.0f;
        if (cell.collectionView.collectionViewLayout) {
            CGSize cs = cell.collectionView.collectionViewLayout.collectionViewContentSize;
            adjustHeight = cs.height;
        }
        height += adjustHeight + 10 + 40;

    } else if (indexPath.section == 2) {//activation
        height = 80.0f;
    } else if (indexPath.section == 3) {//container
        height = 300;
    }

    return height;
}


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

    UITableViewCell *cell = nil;

    NSLog(@"%s\n %zd", __PRETTY_FUNCTION__, indexPath.section);
    if (indexPath.section == 0) {//title

        RulesStaticTitleTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"StaticTitleCellIdentifier"];

        if (tcell == nil) {
            tcell = [[RulesStaticTitleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"StaticTitleCellIdentifier"];
        }
        tcell.lblItemName.text = NSLocalizedString(@"집에 변화가 일어날 때", @"집에 변화가 일어날 때");

        cell = tcell;

    } else if (indexPath.section == 1) {//커맨드클래스 컬렉션뷰
        RegisterCmdClsTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CollectionCellIdentifier"];

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

        cell = tcell;
    } else if (indexPath.section == 2) {//activation
        RegisterTriggerActivationTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"ActivationCellIdentifier"];
        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 == 2) {
        RegisterTriggerActivationTableViewCell *tcell = (RegisterTriggerActivationTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        [self btnAddTriggerOptionTouched:tcell.btnTriggerOption];
    }
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(RegisterCmdClsTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        //set indexpath at collectionview
        [cell setCollectionViewDataSourceDelegate:self indexPath: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 - UICollectionView Delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    NSInteger cellCount = _itemList.count;
    return cellCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *kCellID = @"CmdClsCollectionCellIdentifier";
    RegisterCmdClsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];

    ItemModel *item = _itemList[indexPath.row];
    [cell setBtnItemImage:item.predDevices && item.predDevices.count];

    cell.btnItem.value = item;
    cell.btnItem.value2 = indexPath;

    [cell.btnItem sd_setImageWithURL:[NSURL URLWithString:item.imageFileName] forState:UIControlStateNormal];
    if (![cell.btnItem actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
        [cell.btnItem addTarget:self action:@selector(btnItemTouched:) forControlEvents:UIControlEventTouchUpInside];
    }

    
    
    CGFloat width = ((IPHONE_WIDTH - 48.0f) / 3.0f) - 18.0f;
    cell.constraintBtnItemWidth.constant = (int)width;
    cell.constraintBtnItemHeight.constant = (int)width;

    cell.lblItem.text = item.itemName;

    return cell;
}

- (void)btnItemTouched:(id)sender {
    CustomButton *btnItem = (CustomButton *)sender;

    ItemModel *item = btnItem.value;
    //popup - 사전정의 규칙 디바이스 목록 조회

    CommandClassListPopupView *popup = [[CommandClassListPopupView alloc] initFromNib];
    popup.tmpItem = item;
    [popup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            if (![_currentItem isEqual:item]) {//동일 아이템이 아닐 경우, 변경함.
                _currentItem.predDevices = nil;
                [btnItem faceOffImage];
                [_tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
                _currentItem = item;
            }
        }
    }];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

//    CGRect cr = collectionView.frame;
//    CGFloat width = IPHONE_WIDTH - 48.0f;
//    if (cr.size.width != width) {//not appear yet
//        cr.size.width = width;
//        collectionView.frame = cr;
//    }
//
//    RegisterCmdClsCollectionView *rcollectionView = (RegisterCmdClsCollectionView *)collectionView;
//    ItemModel *item = _itemList[rcollectionView.indexPath.row];
//

    CGFloat width = ((IPHONE_WIDTH - 48.0f) / 3.0f) - 18.0f;
    return CGSizeMake(width, 107);
}


#pragma mark - UI Events
- (IBAction)btnAddTriggerOptionTouched:(id)sender {

    _sectionCount = _sectionCount == 3 ? 4 : 3;
    [_tableView reloadData];

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

- (void)btnSelectTouched:(id)sender {


    //IMPORTANT : 수정모드 일 경우, 기존 컨디션이 사라지는 경우 생김. 아래까지 스크롤이 안된경우,
    //컨디션을 설정함 - 이전 선택된 컨디션을 유지하기 위해 먼저 확인 - 테이블 뷰의 특성상.
    NSMutableArray< ItemModel> *conditions = nil;
    if (_triggervc && [_triggervc hasCondition]) {
        if (!_triggervc.conditions) {
            return;
        }

        conditions = _triggervc.conditions;
    } else {
        if (_tmpItem.predDevices && _tmpItem.predDevices.count && !_triggervc) {
            PredefinedDeviceModel *pdevice = _tmpItem.predDevices[0];
            conditions = pdevice.conditions;
        }
    }

    _tmpItem.predDevices = nil;

    //현재 선택된 아이템을 반환해야함.
    for (ItemModel *item in _itemList) {
        if (item.predDevices && item.predDevices.count) {
            _tmpItem.predItemSequence = item.predItemSequence;
            _tmpItem.predDevices = (NSMutableArray<PredefinedDeviceModel> *)[[NSMutableArray alloc] initWithArray:item.predDevices];
            break;
        }
    }

    //1.validation
    if (!_tmpItem.predDevices || !_tmpItem.predDevices.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"선택된 장치가 없습니다", @"선택된 장치가 없습니다")];
        return;
    }

    if (conditions) {
        PredefinedDeviceModel *pdevice = _tmpItem.predDevices[0];
        pdevice.conditions = conditions;
    }

    [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
