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

#import "RequestHandler.h"
#import "DeviceModel.h"

#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomImageView.h"

#import "ThingsAddStartViewController.h"
#import "ThingsAddViewController.h"
#import "HomeHubSelectPopupView.h"


@implementation ThingsAddTableViewCell

// 가스 밸브 이미지명 : img_things_product_01_smartgasvalve

// 도어센서 이미지 명 : img_things_product_02_mutisensor_door

// 스마트플러그 이미지 명 : img_things_product_03_smartplug

@end

@interface ThingsAddViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSArray *_addableDeviceList;
    DataSelectListModel *_homeHubList;
}
@end


#pragma mark - Class Definition

@implementation ThingsAddViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)initUI {
    [self initTableViewAsDefaultStyle:_tableView];
}

- (void)prepareViewDidLoad {

    _addableDeviceList = @[@{@"deviceName" : @"가스 밸브",
                             @"manufacturer" : @"타임밸브",
                             @"nodeName" : @"스마트 플러그",
                             @"deviceKey": @"36002"},
                           @{@"deviceName" : @"도어 센서",
                             @"manufacturer" : @"타임밸브",
                             @"nodeName" : @"스마트 플러그",
                             @"deviceKey": @"11011"},
                           @{@"deviceName" : @"스마트 플러그",
                             @"manufacturer" : @"타임밸브",
                             @"nodeName" : @"스마트 플러그",
                             @"deviceKey": @"17002"},
                           
                           @{@"deviceName" : @"다우앤텍 멀티 센서",
                             @"manufacturer" : @"다우엔텍",
                             @"nodeName" : @"멀티센서",
                             @"deviceKey": @"11011"}];
    _homeHubList = [[DataSelectListModel alloc] init];
    _homeHubList.title = @"홈허브 선택";
    
    if ([[JDFacade facade].loginUser isMultiHomeHub]) {
        for (DeviceModel *info in [JDFacade facade].loginUser.deviceList) {
            DataSelectModel *data = [[DataSelectModel alloc] init];
            data.title = info.deviceName;
            data.value = info;
            [_homeHubList.list addObject:data];
        }
    }
}

#pragma mark - Main Logic


#pragma mark - UITableView DataSource & Delegate

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ThingsAddTableViewCell *cell = (ThingsAddTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"AddCellIdentifier"];

    NSDictionary *addableDevice = _addableDeviceList[indexPath.row];
    cell.lblDeviceName.text = addableDevice[@"deviceName"];
    cell.lblVendor.text = addableDevice[@"manufacturer"];
    
//    if (![cell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
//        [cell.btnAdd addTarget:self action:@selector(btnAddDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
//    }
    cell.btnAdd.tag = indexPath.row;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
//    NSDictionary *addableDevice = _addableDeviceList[indexPath.row];
    
    [self addDevice:indexPath];
}

#pragma mark - TableView Delegate
- (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)btnAddDeviceTouched:(id)sender {
    UIButton *senderButton = (UIButton *)sender;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:senderButton.tag inSection:0];
    
    [self addDevice:indexPath];
}

-(void)showHomeHubSelect:(NSIndexPath *)indexPath {
    HomeHubSelectPopupView *hpopup = [[HomeHubSelectPopupView alloc] initFromNib];
//    hpopup.refTriggers = _triggers;
//    hpopup.refDevices = _triggerDevices;
//    hpopup.refConditions = _conditions;
    
    [hpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            
            _selectHub = hpopup.selectedDeviceModel;
            [self addDevice:indexPath];
        }
    }];

}


-(void)addDevice:(NSIndexPath *)indexPath
{
    if ([[JDFacade facade].loginUser isMultiHomeHub] && _selectHub == nil) {
        [self showHomeHubSelect:indexPath];
        return;
    }
    
    NSDictionary *info = _addableDeviceList[indexPath.row];
    
    NSLog(@"info : %@", info);
    
    DeviceModel *addDevice = [[DeviceModel alloc] init];
    addDevice.prdName = info[@"deviceName"];
    addDevice.cmdclsTypeId = info[@"deviceKey"];
    
    ThingsAddStartViewController *vc = (ThingsAddStartViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddStartViewController" storyboardName:@"Things"];
    vc.addDevice = addDevice;
    vc.selectHub = _selectHub;
    
    vc.providesPresentationContextTransitionStyle = YES;
    vc.definesPresentationContext = YES;
    
    [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    
    [self presentViewController:vc animated:NO completion:nil];
}

- (IBAction)btnCloseTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

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



@end
