//
//  ActionPopTableView.h
//  kneet
//
//  Created by Jason Lee on 5/15/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "CustomLabel.h"
#import "CustomRadioGroup.h"
#import "CustomImageView.h"
#import "CustomButton.h"

#import "RequestHandler.h"
#import "ItemModel.h"
#import "ActionPopTableView.h"
#import "PredefinedDeviceViewController.h"
#import "RegisterModeViewController.h"
#import "RegisterPushViewController.h"
#import "ImageUtil.h"

#define kfPopTableViewCellHeight 100.0f

@implementation ActionPopTableViewCell


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

@end

@interface ActionPopTableView () <UITableViewDataSource, UITableViewDelegate> {
    NSMutableArray<ItemModel> *_itemList;
    UIImage *_bgCellImage;
    BOOL _isNotFirstLoading;
}

@end

@implementation ActionPopTableView

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"ActionPopTableView"]) {
        if ([view isKindOfClass:[ActionPopTableView class]]) {
            self = (ActionPopTableView *)view;

            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;

            self.lblTitle.text = NSLocalizedString(@"무엇을 실행할까요?",nil);

             if (!self.tableView.delegate) {
                _tableView.dataSource = self;
                _tableView.delegate = self;
             }

            _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            _tableView.separatorColor = kUILineColor2;

            _tableView.backgroundColor = [UIColor clearColor];
            _tableView.scrollEnabled = YES;

            _tableView.tableFooterView = [[UIView alloc] init];

            UINib *nib = [UINib nibWithNibName:@"ActionPopTableViewCell" bundle:nil];
            [_tableView registerNib:nib forCellReuseIdentifier:@"CellIdentifier"];

            UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
            _bgCellImage = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];

            [self performSelector:@selector(requestCommandClassList) withObject:nil afterDelay:0.0f];
            
            [self.btnConfirm setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

- (void)show {
    [super show];

    //FIXME : 수정!!
    if (!self.tableView.delegate) {
        self.tableView.delegate = self;
        self.tableView.dataSource= self;
    }

    [_tableView reloadData];
    [_tableView scrollsToTop];
}


- (void)setActions:(NSArray<ItemModel> *)actions {
    _actions = actions;

    [self matchActionsForCommnadClassList];
}

- (void)awakeFromNib {

}

#pragma mark - Main Logic

//여길 호출해줘야됨.
- (void)requestCommandClassList {
    //parameters
//    NSDictionary *parameter = @{@"homegrp_scene_id": _homeGroupSceneId ? _homeGroupSceneId : ksEmptyString};

    NSString *path = nil;
    if (_isRuleMode) {
        path = [NSString stringWithFormat:API_GET_RULE_CMDCLS, @"02"];
    } else {
        path = [NSString stringWithFormat:API_GET_SCENE_CMDCLS];
    }

    [[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 {
    //이전에 선택된 액션과 액션리스트를 매칭시킴.

    for (ItemModel *action in _actions) {
        NSInteger index = [_itemList indexOfObjectPassingTest:^BOOL(ItemModel *listAction, NSUInteger idx, BOOL *stop) {
            if (_isRuleMode) {
                return [action.predItemSequence isEqualToString:listAction.predItemSequence];
            } else {
                return [action.predActionSequence isEqualToString:listAction.predActionSequence];
            }
        }];

        if (index != NSNotFound) {//FIXME : 교체를 해버리면,, 결국,, 이전데이터가 남아있음.
            ItemModel *listAction = _itemList[index];
            action.totalCnt = listAction.totalCnt;
            
            [_itemList replaceObjectAtIndex:index withObject:action];
        }
    }

    [_tableView reloadData];
}

//- (void)resetAction:(ItemModel *)action {
//    for (ItemModel *listAction in _itemList) {
//        if ([listAction isEqual:action]) {
//            listAction.predDevices = nil;
//            listAction.cnt = @"0";
//            break;
//        }
//    }
//}


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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _itemList.count;
}

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

    static NSString *CellIdentifier = @"CellIdentifier";
    ActionPopTableViewCell *cell = (ActionPopTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    ItemModel *item = _itemList[indexPath.row];
    cell.lblActionName.text = item.itemName;

    NSString *subItemsCount = nil;
    if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
        subItemsCount = [NSString stringWithFormat:@"%zd / %@", item.sumPredDeviceCount, item.totalCnt];

    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드일 경우,
        subItemsCount = [NSString stringWithFormat:@"%zd / %@", item.sumModesCount, item.totalCnt];

    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,

        subItemsCount = [NSString stringWithFormat:@"%zd / %@", item.sumPushesCount, item.totalCnt];
    }

    cell.lblActionCount.text = subItemsCount;
    cell.btnSelect.hidden = ![subItemsCount integerValue];
    if (!cell.btnSelect.hidden) {

        [cell.lblActionName setColor:kUITextColor02 text:cell.lblActionName.text];
        [cell.lblActionCount setColor:kUITextColor02 text:cell.lblActionCount.text];
    }
    cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage];

    return cell;
}

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

    ItemModel *item = _itemList[indexPath.row];
    UIViewController *vc = nil;

    if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스
        PredefinedDeviceViewController *dvc = (PredefinedDeviceViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"PredefinedDeviceViewController" storyboardName:@"Rules"];

        if (!_actions || [_actions indexOfObject:item] == NSNotFound) {//자유 선택 - 최초 생성 시 플래그 설정
            dvc.isCustomCreation = YES;
        }
        dvc.title = [ItemModel itemSubTypeString:item.itemSubTypeCode];

        if (_isRuleMode) {
            dvc.predRuleId = item.predRuleId;
        } else {
            dvc.predSceneId = item.predSceneId;
        }
        dvc.tmpItem = item;

        vc = dvc;

    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//모드
        RegisterModeViewController *mvc = (RegisterModeViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RegisterModeViewController" storyboardName:@"Rules"];

        if (!_actions || [_actions indexOfObject:item] == NSNotFound) {//자유 선택 - 최초 생성 시 플래그 설정
            mvc.isCustomCreation = YES;
        }
        mvc.title = [ItemModel itemSubTypeString:item.itemSubTypeCode];
        mvc.tmpItem = item;

        vc = mvc;
    } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
        RegisterPushViewController *pvc = (RegisterPushViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RegisterPushViewController" storyboardName:@"Rules"];

        if (!_actions || [_actions indexOfObject:item] == NSNotFound) {//자유 선택 - 최초 생성 시 플래그 설정
            pvc.isCustomCreation = YES;
        }
        pvc.title = [ItemModel itemSubTypeString:item.itemSubTypeCode];
        pvc.tmpItem = item;

        vc = pvc;
    }

    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
    [self btnConfirmTouched:nil];
}


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

- (void)btnConfirmTouched:(id)sender {
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;

    [super btnConfirmTouched:sender];
}

- (void)btnCancelTouched:(id)sender {
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;

    [super btnCancelTouched:sender];
}

@end
