//
//  CommandClassListPopupView.h
//  kneet
//
//  Created by Jason Lee on 5/22/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//

#import "JDObject.h"
#import "RequestHandler.h"
#import "ItemModel.h"

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


#import "CommandClassListPopupView.h"
#import "CommandClassControlView.h"
#import "NoContentView.h"
#import "ImageUtil.h"

#define kfPopTableViewCellHeight 100.0f

@implementation CommandClassListCell


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

@end

@interface CommandClassListPopupView () <UITableViewDataSource, UITableViewDelegate, CustomRadioGroupDelegate> {
    NSMutableArray<PredefinedDeviceModel> *_preDeviceList;

    UIImage *_bgCellImage;
    BOOL _isNotFirstLoading;

    CustomRadioReusableGroup *_rgroup;
}

@end

@implementation CommandClassListPopupView

- (id)initFromNib {

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

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

             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:@"CommandClassListCell" 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_01"]];

            _rgroup = [[CustomRadioReusableGroup alloc] init];
            _rgroup.tableView = _tableView;
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"선택", @"선택") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

- (void)didMoveToSuperview {
    //상위 함수를 호출하지 않음.
}

- (void)show {
    [super show];

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

    [_tableView reloadData];
    [_tableView scrollsToTop];
}

- (void)setTmpItem:(ItemModel *)tmpItem {
    _tmpItem = tmpItem;

    self.lblTitle.text = _tmpItem.itemName;
    [self requestPredefinedDevicesByItem];
}


#pragma mark - Main Logic

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

    NSString *path = path = [NSString stringWithFormat:API_GET_PRERULE_DEVICES, _tmpItem.predRuleId, _tmpItem.predItemSequence];

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

    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;
            
            [[JDFacade facade] setRadioButtonStatus:@YES object:tdevice];  //for radio box
        }
    }

    [_tableView reloadData];
}


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

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;

    PredefinedDeviceModel *pdevice = _preDeviceList[indexPath.row];
    height = (!pdevice.predCmdclsValue || [pdevice.predCmdclsValue isEmptyString]) ? 169.0f : 100.0f; //컨트롤을 로드 - 커맨드클래스 밸루 리스트가 있는 장치에 한함.

    return height;
}

- (NSArray<CmdClsValueModel> *)makeCmdClsValueList {

    CmdClsValueModel *cmdCmsValue = [[CmdClsValueModel alloc] init];
    cmdCmsValue.cmdclsValue = @"02";
    cmdCmsValue.cmdclsValueMsg = NSLocalizedString(@"미만 시", @"미만 시");

    CmdClsValueModel *cmdCmsValue2 = [[CmdClsValueModel alloc] init];
    cmdCmsValue2.cmdclsValue = @"04";
    cmdCmsValue2.cmdclsValueMsg =  NSLocalizedString(@"초과 시", @"초과 시");

    return (NSMutableArray<CmdClsValueModel> *)[[NSMutableArray alloc] initWithArray:@[cmdCmsValue, cmdCmsValue2]];
}

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

    static NSString *CellIdentifier = @"CellIdentifier";
    CommandClassListCell *tcell = (CommandClassListCell *)[tableView dequeueReusableCellWithIdentifier: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;

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

    [_rgroup addRadioButton:tcell.rdoSelect];

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

    [[tcell.controlContainerView2 subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIView *subview = (UIView *)obj;
        [subview removeFromSuperview];
    }];

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

        CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:CmdClsTypeThermostatSetPoint];
        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);
            }];
        }

        CommandClassControlView *controlView2 = [CommandClassControlView viewForCommandClass:CmdClsTypeThermostatMode];
        if (!pdevice.cmdclsValueList || !pdevice.cmdclsValueList.count) {
            pdevice.cmdclsValueList = [self makeCmdClsValueList];
        }

        controlView2.device = pdevice; //02, 04
        controlView2.isConditionMode = YES;
        controlView2.isConditionTypeMode = YES;
        controlView2.enable = pdevice.enable;

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

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

    tcell.backgroundColor = [UIColor clearColor];
    tcell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage];

    return tcell;
}

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


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

    tcell.rdoSelect.value = pdevice;
    [_rgroup someRadioButtonTouched:tcell.rdoSelect];
}


- (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 - UI Events
- (void)btnConfirmTouched:(id)sender {

    if (_rgroup.values && _rgroup.values.count) {
        PredefinedDeviceModel *predDevice = _rgroup.valueForChecked;
        _tmpItem.predDevices = (NSMutableArray<PredefinedDeviceModel> *)[[NSMutableArray alloc] initWithArray:@[predDevice]];
    }

    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;

    [super btnConfirmTouched:sender];
}

- (void)btnCancelTouched:(id)sender {
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
//    self.tableView = nil;
    [super btnCancelTouched:sender];
}

@end
