//
//  ThingsAddWallPadSubTypeViewController.m
//  kneet
//
//  Created by Jason Lee on 7/21/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "RequestHandler.h"
#import "DeviceModel.h"
#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomRadioGroup.h"


#import "ThingsAddWallPadSubTypeViewController.h"
#import "UIImageView+WebCache.h"
#import "ThingsDetailViewController.h"
#import "ThingsViewController.h"
#import "ImageUtil.h"

@implementation WallpadSubTypeTitleViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

@end

@implementation WallpadSubTypeTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}


@end

@interface ThingsAddWallPadSubTypeViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSArray<DeviceModel> *_deviceList;
    
    CustomRadioReusableGroup *_rgroup;
    BOOL _isNotFirstLoading;
    UIImage *_bgCellImage1, *_bgCellImage2;
    NSString *_titleDesc;
}
@end


#pragma mark - Class Definition

@implementation ThingsAddWallPadSubTypeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // initialize
    _rgroup = [[CustomRadioReusableGroup alloc] init];
    _rgroup.tableView = _tableView;
    
    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    
    
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.separatorColor = kUILineColor2;
    _tableView.backgroundColor = [UIColor clearColor];
    
    _tableView.tableFooterView = [[UIView alloc] init]; //this call table events;
    
    //Localization
    [_btnConfirm 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_02"]];
    _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
    
    if ([[JDFacade facade] viewControllerOnNaviationController:[ThingsDetailViewController class]]) {
        _titleDesc = NSLocalizedString(@"장치의 유형을 선택해주세요", @"장치의 유형을 선택해주세요");
    } else {
        _titleDesc = NSLocalizedString(@"'%@'\n장치가 추가되었습니다\n\n장치의 유형을 선택해주세요", @"'%@'\n장치가 추가되었습니다\n\n장치의 유형을 선택해주세요");
    }
}

- (void)prepareViewDidLoad {
    [self requestDevcieTypes];
}

#pragma mark - Main Logic

- (void)requestDevcieTypes {
    //parameters
    NSString *path = [NSString stringWithFormat:API_GET_DEVICE_TYPES, _device.deviceId];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[DeviceListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DeviceListModel *deviceList = (DeviceListModel *) responseObject;
        
        if (deviceList && deviceList.list && deviceList.list.count) {//API 성공 ,
            _deviceList = deviceList.list;
        }
        
        [_tableView reloadData];
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestChangeDeviceType {
    //parameters
    DeviceModel *profile = _rgroup.valueForChecked;
    NSDictionary *parameter = @{@"device_profile_id": profile.deviceProfileId};
    
    NSString *path = [NSString stringWithFormat:API_POST_DEVICE_TYPES, _device.deviceId];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {

        ThingsDetailViewController *tvc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsDetailViewController class]];
        if (tvc) {
            [tvc prepareViewDidLoad]; //디바이스 상세 리로드
            
            ThingsViewController *svc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
            if (svc) {
                [svc prepareViewDidLoad];
            }
            
            [[JDFacade facade] dismissViewControllerByPush:self completion:^{
                [[JDFacade facade] toast:NSLocalizedString(@"변경되었습니다", @"변경되었습니다")];
            }];
            
        }else {
            UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
            [[JDFacade facade] presentViewControllerByPush:vc pvc:self];               
        }

    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];

}

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

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0) {//title
        height = ![[JDFacade facade] viewControllerOnNaviationController:[ThingsDetailViewController class]] ? 140 : 100;
    } else if (indexPath.section == 1) {//modes
        height = 100;
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    NSInteger section = indexPath.section;
    if (section == 0) {
        WallpadSubTypeTitleViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        
        if ([[JDFacade facade] viewControllerOnNaviationController:[ThingsDetailViewController class]]) {
            tcell.constraintLblTitleTop.constant = 30;
            tcell.lblDesc.text = _titleDesc;
        } else{
            tcell.lblDesc.text = [NSString stringWithFormat:_titleDesc, _device.deviceName];
        }
        
        cell = tcell;
    } else if (section == 1) {
        WallpadSubTypeTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
     
        DeviceModel *profile = _deviceList[indexPath.row];
        
        [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:profile.imageFileName]];
        tcell.lblType.text = profile.profileName;
        tcell.rdoSelect.value = profile;
        
        if (indexPath.row == 0 && !_isNotFirstLoading) {
            _isNotFirstLoading = YES;
            tcell.rdoSelect.checked = YES;
        } else {
            tcell.rdoSelect.checked = [tcell.rdoSelect getRadioStatusFromValue];
        }
        
        [_rgroup addRadioButton:tcell.rdoSelect];
        
        cell = tcell;
        
        //set background image
        if (indexPath.row % 2 == 1) {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage1];
        } else {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage2];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        WallpadSubTypeTableViewCell *tcell = (WallpadSubTypeTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        [_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
- (IBAction)btnConfirmTouched:(id)sender {
    [self requestChangeDeviceType];
}


#pragma mark - MemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
