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

#import "HomeHubSearchViewController.h"

@interface HomeHubSearchViewController () {
    
    NSTimer *_timer;
    NSInteger _elapsedSeconds;
    
    BLEServiceHandler *bleService;
}

@end

@implementation HomeHubSearchViewController

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


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    bleService.delegate = self;
    [self initUI];
    
    UIViewController *vc = [CommonUtil currentViewController];
    NSLog(@"vc : %@", vc);
    NSLog(@"navi : %@", vc.navigationController);
    NSLog(@"vc navi cons : %@", vc.navigationController.viewControllers);
}

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


- (void)initUI {
    
    [self startLoading:YES];
    [bleService startScan];
}

- (void)prepareViewDidLoad {
    
    //ble
    bleService = [BLEServiceHandler sharedManager];
    
}

-(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--;
        _lblTimer.text = [NSString stringWithFormat:@"%zd", _elapsedSeconds];
        
        //            if (_elapsedSeconds == 0) {
        //                [self finishDeviceDel:NO];
        //            }
    });
}


#pragma mark - ble service delegate
- (void)BLEEndScan:(NSMutableArray *)devices {
    
    [self startLoading:NO];

    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubSearchSuccessViewController" storyboardName:@"HomeHub"];
    
    if (devices.count == 0) {
        
        vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubSearchFailViaewController" storyboardName:@"HomeHub"];
        
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    else if(devices.count > 1) {
        
        [[JDFacade facade] alertTitle:@"Notice"
                              message:@"홈허브 인터넷 연결 설정은 한 개씩 진행하세요(준비 중인 홈허브가 두 개 이상일 경우 오류 처리됩니다.)"
                     completionHander:^{
                         
                         [self.navigationController popViewControllerAnimated:YES];
                     }];
        return;
    }
    
    [self.navigationController pushViewController:vc animated:NO];
}


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

#pragma mark - User Event
- (IBAction)btnCloseTouched:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
