//
//  DeviceNodePopupView.m
//  kneet2
//
//  Created by Jason Lee on 11/5/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

#import "RequestHandler.h"
#import "JDJSONModel.h"

#import "CustomLabel.h"
#import "CustomTextField.h"
#import "CustomTableView.h"
#import "CustomImageView.h"
#import "CustomButton.h"
#import "CustomCheckBox.h"

#import "ValidateUtil.h"
#import "ImageUtil.h"
#import "UIImageView+WebCache.h"

#import "DeviceNodePopupView.h"
#import "CustomRadioGroup.h"
#import "CommandClassControlNodeView.h"

@implementation DeviceNodePopupTableViewCell

@end

@interface DeviceNodePopupView () <UITableViewDataSource, UITableViewDelegate, CustomCheckBoxDelegate> {
    CustomRadioReusableGroup *_rgroup;
    
    BOOL _isNotFirstLoading;
    UIImage *_bgCellImage1, *_bgCellImage2;
}

@end

@implementation DeviceNodePopupView

- (id)initFromNib {

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

            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            
            [self initTableViewAsDefaultStyle:_tableView];
            
            UINib *nib = [UINib nibWithNibName:@"DeviceNodePopupTableViewCell" bundle:nil];
            [_tableView registerNib:nib forCellReuseIdentifier:@"NodeCellIdentifier"];
            
            //set radio group
            _rgroup = [[CustomRadioReusableGroup alloc] init];
            _rgroup.tableView = _tableView;
            
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
            
            UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
            _bgCellImage1 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
            _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];

        }
    }

    return self;
}

- (void)initTableViewAsDefaultStyle:(CustomTableView *)tableView {
    tableView.dataSource = self;
    tableView.delegate = self;
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = [UIColor clearColor];
    
    tableView.tableFooterView = [[UIView alloc] init]; //this call table events;
}

- (void)didMoveToSuperview {

}

- (void)setItem:(ItemModel *)item {
    _item = item;
    
    self.lblTitle.text = item.sourceName;
    [self.imgvDevice sd_setImageWithURL:[NSURL URLWithString:item.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
    
    [_tableView reloadData];
}

#pragma mark - Main Logic



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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _item.subItems ? _item.subItems.count : 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 110.0f;
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ItemSubModel *subItem = _item.subItems[indexPath.row];
    
    DeviceNodePopupTableViewCell *tcell = (DeviceNodePopupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"NodeCellIdentifier"];
    
    tcell.lblNodeName.text = subItem.sourceSubName;
    
    //1.set node
    
    //뷰를 초기화함.
    [[tcell.controlContainer subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIView *subview = (UIView *)obj;
        [subview removeFromSuperview];
    }];
    
    CommandClassControlNodeView *controlView = [CommandClassControlNodeView viewForCommandClass:subItem.cmdclsType];
    controlView.subItem = subItem;
    
    tcell.controlContainer.hidden = !controlView;
    if (!tcell.controlContainer.hidden) {
        UIView *superview = tcell.controlContainer;
        [superview addSubview:controlView];
        
        [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(controlView.frame.size);
            make.center.equalTo(superview);
        }];
    }

    
    
    if ([_typeCode isEqualToString:ksItemTypeCodeTrigger] || [_typeCode isEqualToString:ksItemTypeCodeCondition]) {//트리거 또는 컨디션
        tcell.chkSelect.hidden = YES;
        
        tcell.rdoSelect.value = subItem;
        if (indexPath.row == 0 && !_isNotFirstLoading) {
            _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 = subItem;
        tcell.chkSelect.checked = [tcell.chkSelect getCheckStatusFromValue];
    }
    
    return tcell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DeviceNodePopupTableViewCell *tcell = (DeviceNodePopupTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    if ([_typeCode isEqualToString:ksItemTypeCodeTrigger] || [_typeCode isEqualToString:ksItemTypeCodeCondition]) {
        [_rgroup someRadioButtonTouched:tcell.rdoSelect];
        
    } else if ([_typeCode isEqualToString:ksItemTypeCodeAction]) {
        [tcell.chkSelect checkBoxClicked];
        
    }
    [_tableView reloadData];
}


- (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 {
    [_tableView reloadData];
}


#pragma mark - UI Events
- (IBAction)btnConfirmTouched:(id)sender {
    
    //validate
    if ([_typeCode isEqualToString:ksItemTypeCodeAction]) {//디바이스 멀티
        
        //FIXME : 사용하게 될경우,
        NSArray *matchedSubItems = [_item.subItems matchedObjectName:ksCustomCheckBoxStatus condition:YES];
        BOOL isSelected = matchedSubItems && matchedSubItems.count;
        
        if (!isSelected) {
            [[JDFacade facade] alert:NSLocalizedString(@"선택된 항목이 없습니다", @"선택된 항목이 없습니다")];
            return;
        }
    } else {//동일한 노드의 액션이 이미 선택되었는지 체크,
        
        ItemSubModel *subItem = _rgroup.valueForChecked;
        
        CmdClsValueModel *cmdclsValue = nil;
        for (cmdclsValue in subItem.cmdclsValueList) {
            if (!_isModifyMode && cmdclsValue.isSelected) {
                [[JDFacade facade] toast:@"이미 추가되어 있습니다"];
                return;
            }
            
            cmdclsValue.isSelected = [[JDFacade facade] getRadioButtonStatus:cmdclsValue];
        }
    }
    
    [super btnConfirmTouched:sender];
}



@end
