//
//  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 "ThingsAddViewController.h"
#import "ThingsAddWallpadSubViewController.h"


@interface ThingsAddViewController () {
    NSInteger _rowCount;
}
@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];

    self.title = NSLocalizedString(@"새 장치 추가",nil);
}

- (void)initUI {
    
    

    //set tableview option
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.backgroundColor = kUILineColor2;

    self.tableView.tableFooterView = [[UIView alloc] init]; //this call table events;
    
    //Localization
    _lblCommaxTitle.text = NSLocalizedString(@"COMMAX 월패드", @"COMMAX 월패드");
    _lblCommaxInfo.text = NSLocalizedString(@"월패드에서 했던 일들을 앱으로도 할 수 있게 됩니다", @"월패드에서 했던 일들을 앱으로도 할 수 있게 됩니다");
    
    _lblCommaxSubTitle.text = NSLocalizedString(@"COMMAX 추가 연결제품", @"COMMAX 추가 연결제품");
    _lblCommaxSubInfo.text = NSLocalizedString(@"월패드에 더 많은 장치를 연결해보세요", @"월패드에 더 많은 장치를 연결해보세요");
    
    _lblDawonPlugTitle.text = NSLocalizedString(@"DAWON 스마트플러그", @"DAWON 스마트플러그");
    _lblDawonPlugInfo.text = NSLocalizedString(@"멀리 있어도 켜고 끌 수 있고 전력량까지 알 수 있습니다", @"멀리 있어도 켜고 끌 수 있고 전력량까지 알 수 있습니다");
    
    _lblFoscamTitle.text = NSLocalizedString(@"FOSCAM (MJPEG 지원모델)", @"FOSCAM (MJPEG 지원모델)");
    _lblFoscamInfo.text = NSLocalizedString(@"어디서나 홈의 상황을 모니터링 할 수 있게 됩니다", @"어디서나 홈의 상황을 모니터링 할 수 있게 됩니다");
    
    _lblGeofenceTitle.text = NSLocalizedString(@"스마트폰 위치센서", @"스마트폰 위치센서");
    _lblGeofenceInfo.text = NSLocalizedString(@"귀가/외출 시 자동실행되는 규칙을 만들 수 있게 됩니다", @"귀가/외출 시 자동실행되는 규칙을 만들 수 있게 됩니다");
}

- (void)prepareViewDidLoad {
    _rowCount = [JDFacade facade].loginHomeGroup.level > 10 ? 5 : 1;    //사용자 권한 별
}

#pragma mark - Main Logic


#pragma mark - UITableView DataSource & Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    
    return _rowCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    if (_rowCount == 1) {//심플 유저인 경우,
        NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:4 inSection:0];
        cell = [super tableView:tableView cellForRowAtIndexPath:tmpIndexPath];
    } else {//마스터, 파워 유저,
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    
    return cell;
}

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

    __block UIViewController *vc = nil;
    
    if (_rowCount == 1) {//심플 유저인 경우,
//        if ([JDFacade facade].loginHomeGroup.deviceId && ![[JDFacade facade].loginHomeGroup.deviceId isEmptyString]) {
//            [[JDFacade facade] alert:NSLocalizedString(@"이미 등록하셨습니다", @"이미 등록하셨습니다")];
//            return;
//        }
        
        vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddGeofencingViewController" storyboardName:@"Things"];

    } else {//마스터, 파워 유저,
        if (indexPath.row == 0) {//wallpad
            vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddWallpadViewController" storyboardName:@"Things"];
        }  else if (indexPath.row == 1) {//wallpad append devices.
            
            NSString *path = [NSString stringWithFormat:API_GET_GROUPS_DEVICES];        
            dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
                GroupsListModel *groupList = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil 
                                                                                      modelClass:[GroupsListModel class] showLoadingView:@(NO)];
                
                NSMutableDictionary *wallpads = nil;
                if (groupList && groupList.groups && groupList.groups.count) {
                    for (GroupsModel *group in groupList.groups) {
                        for (DeviceModel *device in group.devices) {//월패드가 등록되었는 지 확인
                            if ([device.deviceProtocolType isEqualToString:@"COMMAX"] && [device.deviceType isEqualToString:@"CONTROLLER_PRIMARY"]) {
                                
                                if (!wallpads) {
                                    wallpads = [[NSMutableDictionary alloc] init];
                                }
                                
                                [wallpads setObject:device.deviceName forKey:device.deviceId];
                            }
                        }
                    }
                }
                
                if (wallpads && wallpads.count) {
                    ThingsAddWallpadSubViewController *tvc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddWallpadSubViewController" storyboardName:@"Things"];
                    tvc.wallpads = wallpads;
                    
                    vc = tvc;
                } else {
                    [[JDFacade facade] toast:NSLocalizedString(@"월패드 등록을 먼저 진행해주세요", @"월패드 등록을 먼저 진행해주세요")];
                    return;
                }
            });
            
        } else if (indexPath.row == 2) {//plug
            vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddPlugViewController" storyboardName:@"Things"];
        } else if (indexPath.row == 3) {//camera
            vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCameraViewController" storyboardName:@"Things"];
        } else if (indexPath.row == 4) {//phone
            
//            if ([JDFacade facade].loginHomeGroup.deviceId && ![[JDFacade facade].loginHomeGroup.deviceId isEmptyString]) {
//                [[JDFacade facade] alert:NSLocalizedString(@"이미 등록하셨습니다", @"이미 등록하셨습니다")];
//                return;
//            }
            
            vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddGeofencingViewController" storyboardName:@"Things"];
        }
    }
    
   
    if (vc) {
        if (self.navigationController) {
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            UINavigationController *nc = [[UINavigationController alloc] init];
            nc.viewControllers = @[vc];
            [[JDFacade facade] presentViewControllerByPush:nc pvc:self];
        }
    }
}

#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



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

@end
