//
//  HomeHubSearchSuccessViewController.m
//  OneCable
//
//  Created by nComz on 2017. 5. 11..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "HomeHubSearchSuccessViewController.h"
#import "CustomTableView.h"
#import "CustomCheckBox.h"
#import "HomeHubConnectWifiViewController.h"

@interface HomeHubSearchSuccessViewController ()<CustomCheckBoxDelegate> {
    
    BLEServiceHandler *bleService;
    NSMutableArray *devices;
    NSArray *_tableZombieValues;
    BTLEDeivceModel *selectedModel;

    NSTimer *_timer;
    NSInteger _elapsedSeconds;
}

@end

@implementation HomeHubSearchTableViewCell

@end

@implementation HomeHubSearchSuccessViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self prepareViewDidLoad];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

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

}

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

- (void)initUI {

    _btnNext.enabled = NO;
    _imgvLoading.hidden = YES;
    
    [self initTableViewAsDefaultStyle:_tableView];
}

- (void)prepareViewDidLoad {
    
    //ble
    bleService = [BLEServiceHandler sharedManager];
    
    devices = [bleService getDeviceList];
    
    if (devices != nil && devices.count > 0) {
        
        selectedModel = [devices objectAtIndex:0];
        _btnNext.enabled = YES;
    }
    
    [_tableView reloadData];
}


-(void)startLoading:(BOOL)isStart {
    
    _lblTimer.hidden = !isStart;
    _imgvLoading.hidden = !isStart;
    
    if (isStart) {
        
        _elapsedSeconds = kMaxTimeOut;
        _lblTimer.text = [NSString stringWithFormat:@"%zd", _elapsedSeconds];
        if (!_timer) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateInclusionStatus) userInfo:nil repeats:YES];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if ([_imgvLoading.layer animationForKey:@"SpinAnimation"] == nil) {
                CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
                animation.fromValue = [NSNumber numberWithFloat:0.0f];
                animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
                animation.duration = 2.0f;
                animation.repeatCount = INFINITY;
                [_imgvLoading.layer addAnimation:animation forKey:@"SpinAnimation"];
            }
        });
    }
    else {
        
        _elapsedSeconds = kMaxTimeOut;
        
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
        
        if ([_imgvLoading.layer animationForKey:@"SpinAnimation"] != nil) {
            [_imgvLoading.layer removeAnimationForKey:@"SpinAnimation"];
        }
    }
}

- (void)updateInclusionStatus {
    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        
        _elapsedSeconds--;
        if (_elapsedSeconds == 0) {
            
        }
    });
}

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

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

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

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

    BTLEDeivceModel *bleModel = [devices objectAtIndex:indexPath.row];
    
    cell.lblHubName.text = bleModel.peripheralRef.name;
    cell.lblSerialNum.text = [NSString stringWithFormat:@"S/N : %@",bleModel.peripheralRef.identifier];
    cell.chkBtn.selected = [selectedModel isEqual:bleModel];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    
    selectedModel = [devices objectAtIndex:indexPath.row];
    _btnNext.enabled = YES;
    [tableView reloadData];
}


#pragma mark - User Event
- (IBAction)btnNextTouched:(id)sender {
    
    NSLog(@"selectedModel : %@", selectedModel);
    
    if (selectedModel != nil) {
        
        //[bleService setConDevice:selectedModel];
        
        [bleService connect:selectedModel];
         [self startLoading:YES];
        
    }

}

- (IBAction)btnCloseTouched:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}


#pragma mark - ble service delegate
- (void)BLEConnected:(BTLEDeivceModel *)info {
    
    NSLog(@"home hub wifi search view connected!") ;
    
    [self startLoading:NO];
    
    HomeHubConnectWifiViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubConnectWifiViewController" storyboardName:@"HomeHub"];
    vc.selectedModel = selectedModel;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)BLEDisConnected:(BTLEDeivceModel *)info {
    
    [self startLoading:NO];
    
    [[JDFacade facade] toast:@"홈허브와 연결할 수 없습니다."];
    [self.navigationController popToRootViewControllerAnimated:YES];
}


@end
