//
//  HomeHubViewController.m
//  kneet2
//
//  Created by Jason Lee on 10/28/15.
//  Copyright © 2015 ntels. All rights reserved.
//

#import "HomeHubViewController.h"
#import "RequestHandler.h"
#import "DeviceModel.h"
#import "CustomTableView.h"
#import "CustomButton.h"
#import "Reachability.h"
#import "ChangeDeviceNamePopupView.h"
#import "HomeHubUpdateGuideViewController.h"
#import "HomeHubUpdateStartViewController.h"

//#import <LGBluetooth/LGBluetooth.h>


@implementation HomeHubTableViewCell

@end

@implementation HomeHubRegistTableViewCell

- (void)didMoveToSuperview {

    [self layoutIfNeeded];
}
@end

@implementation HomeHubInfoTableViewCell

@end

@interface HomeHubViewController () {
    
    BOOL bleState;
    DeviceModel *hubInfo;
    BLEServiceHandler *bleService;
}
@end

#pragma mark - Class Definition



@implementation HomeHubViewController 


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

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    bleService.delegate = self;
    bleState = [[BLEServiceHandler sharedManager] checkBLEStatus];

    [self refreshData];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    bleService.delegate = nil;
}

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

- (void)initUI {

    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    statusBar.backgroundColor = [UIColor whiteColor];
    
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [self initTableViewAsDefaultStyle:_tableView];
}

- (void)prepareViewDidLoad {

    //ble
    bleState = NO;
    bleService = [BLEServiceHandler sharedManager];
}

- (void)updateHomeHubStatus {
    
    [self refreshData];
}

- (void)refreshData {
    
    if (_selectHub == nil) {
        hubInfo = [[JDFacade facade].loginUser getHomeHub];
    } else {
        hubInfo = [[JDFacade facade].loginUser getHomeHub:_selectHub.deviceId];
    }
    
    [[JDFacade facade].loginUser setHomeHubID:hubInfo.deviceId];
    _lblTitle.text = hubInfo.deviceName;
    
    NSLog(@"homehubVC hubinfo : %@",hubInfo);
    [_tableView reloadData];
}


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

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat height = 86.0f;
    
    if (indexPath.row == 0) {
        height = 185.0f;
    } else if (indexPath.row == 1){
        height = hubInfo.isUpdateNeed ? 219.0f : 182.0f;
    } else if (indexPath.row == 2){
        height = 164.0f;
    }
    
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    
    if (indexPath.row == 0) {
        HomeHubTableViewCell *tcell = (HomeHubTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HubCellIdentifier"];
        
        if (![tcell.btnSet actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnSet addTarget:self action:@selector(btnSetTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        [self masterBtn:tcell.btnSet];
        
        if ([hubInfo isDeviceOnlined]) {
            tcell.lblNetworkStatus.text = @"온라인";
            tcell.lblBrokenTime.text = @"";
            tcell.lblNetworkStatus.textColor = kUITextColor04;
            tcell.imgvStatus.hidden = YES;
        } else {
            tcell.lblNetworkStatus.text = @"오프라인";
            tcell.lblBrokenTime.text = [CommonUtil connectDataFromStr:hubInfo.deviceOnlineLastDatetime];
            tcell.lblNetworkStatus.textColor = kUITextColor07;
            tcell.lblBrokenTime.textColor = kUITextColor07;
            tcell.imgvStatus.hidden = NO;
        }
            
        
        if([hubInfo isDeviceConn]){
            
            tcell.lblDeviceStatus.text = @"온라인";
            tcell.lblDeviceStatus.textColor = kUITextColor04;
        } else {
            tcell.lblDeviceStatus.text = @"오프라인";
            tcell.lblDeviceStatus.textColor = kUITextColor07;
        }
        
        cell = tcell;
    } else if (indexPath.row == 1) {
        HomeHubRegistTableViewCell *tcell = (HomeHubRegistTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"RegistCellIdentifier"];
        

        tcell.lblFirmCurrentVer.text = [NSString stringWithFormat:@"현재%@/최신%@",  hubInfo.firmwareVersion,hubInfo.lastFirmwareVersion];
        tcell.lblSoftCurrentVer.text = [NSString stringWithFormat:@"현재%@/최신%@",  hubInfo.softwareVersion,hubInfo.lastSoftwareVersion];
        
        
        tcell.viewUpdate.hidden = !hubInfo.isUpdateNeed;
        
        if (hubInfo.isUpdateSoftware) {
            
            tcell.lblUpdate.text = [NSString stringWithFormat:@"소프트웨어: 업데이트 버전%@",
                                    hubInfo.lastSoftwareVersion];
        }
        if (hubInfo.isUpdateFirmware) {
            
            tcell.lblUpdate.text = [NSString stringWithFormat:@"펌웨어: 업데이트 버전%@",
                                    hubInfo.lastFirmwareVersion];
        }
        
        [self masterBtn:tcell.btnSoftUpdate];

        if (![tcell.btnSoftUpdate actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnSoftUpdate addTarget:self action:@selector(btnSofrwareUpdateTouched:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell = tcell;
        
    } else if (indexPath.row == 2) {
        HomeHubInfoTableViewCell *tcell = (HomeHubInfoTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HubInfoCellIdentifier"];

        tcell.lblModelName.text = hubInfo.deviceModelId;
        tcell.lblSerialNum.text = hubInfo.deviceSn;
        
        cell = tcell;
    }
    
    return cell;
}

- (void)masterBtn:(CustomButton *)button{
    if ([JDFacade facade].loginUser.level < 90) {
        button.hidden = YES;
    } else {
        button.hidden = NO;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
}


- (void)changeDeviceName:(NSString *)deviceName {
    
    _lblTitle.text = deviceName;
    
    NSMutableArray *deviceList = [[JDFacade facade].loginUser.deviceList mutableCopy];
    
    for (NSInteger i = 0;i<deviceList.count;i++) {

        DeviceModel *device = [deviceList objectAtIndex:i];
        
        if (EQUALS(device.deviceId, _selectHub.deviceId)) {
            
            DeviceModel *newDeviceModel = [[DeviceModel alloc] initWithDeviceModel:device deviceName:deviceName];
            [deviceList replaceObjectAtIndex:i withObject:newDeviceModel];
        }
    }
    
    [[JDFacade facade].loginUser setDeviceList:deviceList];
}

#pragma mark User Event
- (IBAction)btnEditTitleTouched:(id)sender {
    
    ChangeDeviceNamePopupView *popup = [[ChangeDeviceNamePopupView alloc]initFromNib:[DeviceDetailModel new]];
    [popup show];
}

- (void)btnSetTouched:(id)sender {
    
    if (bleState) {
        
        UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubSearchViewController" storyboardName:@"HomeHub"];
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        
        bleState = [[BLEServiceHandler sharedManager] checkBLEStatus] ;
    }
}

//펌웨어 or 소프트웨어 업데이트
- (void)btnSofrwareUpdateTouched:(id)sender{

    NSInteger updateType = UPDATE_ALL;
    
    if (hubInfo.isUpdateFirmware && !hubInfo.isUpdateSoftware)
        updateType = UPDATE_FIRMWARE;
    else if (!hubInfo.isUpdateFirmware && hubInfo.isUpdateSoftware)
        updateType = UPDATE_SOFTWARE;
    
    HomeHubUpdateGuideViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubUpdateGuideViewController" storyboardName:@"HomeHub"];
    vc.updateType = updateType;
    vc.hubInfo = hubInfo;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UI Events
- (IBAction)btnSecureTouched:(id)sender {
    
}

- (void)btnCloseTouched:(id)sender {
    
    if ([[JDFacade facade].loginUser isMultiHomeHub])
        [self.navigationController popViewControllerAnimated:YES];
    else
        [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark - ble service delegate
- (void)BLEStateChange:(BOOL)state {

    bleState = state;

}


#pragma mark - SocketService
-(void) receiveSocketData:(NSNotification *)notification {
    
    SocketModel *result = [[SocketModel alloc] initWithDictionary:notification.object error:nil];
    //NSLog(@"receiveSocketData Result : %@", result);
    
    [self processSocket:result];
}

- (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result {
    
    //NSLog(@"receiveSocketData Result : %@", result);
    
    [self processSocket:result];
}

- (void)processSocket:(SocketModel*)result {
    
    if (EQUALS(result.messageType, MSG_TYPE_DEVICE_CONN) ||
        EQUALS(result.messageType, MSG_TYPE_DEVICE_CONTENT)) {

        [self performSelector:@selector(refreshData) withObject:nil afterDelay:1.0f];
    }
}



@end
