//
//  HomeHubSelectPopupView.m
//  OneCable
//
//  Created by KaRam Kim on 2017. 5. 31..
//  Copyright © 2017년 ntels. All rights reserved.
//
#import "JDObject.h"

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

#import "CustomLabel.h"
#import "CustomTableView.h"
#import "CustomButton.h"
#import "CustomRadioGroup.h"
#import "ImageUtil.h"


#import "HomeHubSelectPopupView.h"

@implementation HomeHubSelectPopupTableViewCell

@end

@interface HomeHubSelectPopupView () <UITableViewDataSource, UITableViewDelegate> {
    
    CustomRadioReusableGroup *_rgroup;
    BOOL _isNotFirstLoading;
    UIImage *_bgCellImage1, *_bgCellImage2, *_bgCellImage3;
    
    NSArray *_deviceList;
}

@end

@implementation HomeHubSelectPopupView

- (id)initFromNib {
    
    for (UIView *view in [CommonUtil nibViews:@"HomeHubSelectPopupView"]) {
        if ([view isKindOfClass:[HomeHubSelectPopupView class]]) {
            self = (HomeHubSelectPopupView *)view;
            
            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            
            [self initTableViewAsDefaultStyle:_tableView];
            
            UINib *nib = [UINib nibWithNibName:@"HomeHubSelectPopupTableViewCell" bundle:nil];
            [_tableView registerNib:nib forCellReuseIdentifier:@"HomeHubCellIdentifier"];
            
            //set radio group
            _rgroup = [[CustomRadioReusableGroup alloc] init];
            _rgroup.tableView = _tableView;
            
            [self.imgTitleBar setImage:[UIImage imageNamed:@"img_popup_bg_head"]inset:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right"] forState:UIControlStateDisabled capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
            
            UIEdgeInsets insets = UIEdgeInsetsMake(1, 1, 1, 2);
            _bgCellImage1 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"common_bg_list_02"]];
            _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"img_list_bg_02"]];
            _bgCellImage3 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"color_bg_01_dis"]];
            
            _deviceList = [JDFacade facade].loginUser.deviceList;
            
            self.btnConfirm.enabled = NO ;
        }
    }
    
    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 {
    
}

- (CommonCode *)weatherLocation {
    return _rgroup.valueForChecked;
}


#pragma mark - Main Logic


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

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DeviceModel *info = _deviceList[indexPath.row];
    
    HomeHubSelectPopupTableViewCell *tcell = (HomeHubSelectPopupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeHubCellIdentifier"];
    tcell.lbTitle.text = info.deviceName;
    tcell.lbSerial.text = [NSString stringWithFormat:@"S/N : %@", info.deviceSn];
    tcell.lbDesc.text = [NSString stringWithFormat:@"추가 가능한 장치 수량 %@", info.remainCtrtCnt];
    tcell.btnRadio.value = info;
 
    tcell.btnRadio.checked = [tcell.btnRadio getRadioStatusFromValue];
//    if (indexPath.row == 0 && !_isNotFirstLoading) {
//        _isNotFirstLoading = YES;
//        tcell.btnRadio.checked = YES;
//    } else {
//       NSLog(@"%@", BOOLToString([tcell.btnRadio getRadioStatusFromValue]));
//        tcell.btnRadio.checked = [tcell.btnRadio getRadioStatusFromValue];
//    }
    
    if ([info.remainCtrtCnt integerValue] < 1 || !info.isDeviceOnlined) {
        tcell.btnRadio.enabled = NO;
    }
    
    
    
    [_rgroup addRadioButton:tcell.btnRadio];
    
    //set background image
//    if (indexPath.row % 2 == 0) {
//        tcell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage1];
//    } else {
//        tcell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage2];
//    }
    if (tcell.btnRadio.enabled) {
        if (tcell.btnRadio.checked) {
            tcell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage1];
        } else {
            tcell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage2];
        }
    } else {
        tcell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage3];
        tcell.lbTitle.textColor = kUITextColor08;
        tcell.lbSerial.textColor = kUITextColor08;
        tcell.lbDesc.textColor = kUITextColor08;
        
    }
        
    
    return tcell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HomeHubSelectPopupTableViewCell *tcell = (HomeHubSelectPopupTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
  
    if (tcell.btnRadio.enabled) {
        
        self.btnConfirm.enabled = YES;
        self.selectedDeviceModel = [_deviceList objectAtIndex:indexPath.row];
        
        [_rgroup someRadioButtonTouched:tcell.btnRadio];
        [_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];
    }
}

@end
