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

#import "HomeHubWifiSearchViewController.h"
#import "HomeHubWifiSearchSuccessViewController.h"

@interface HomeHubWifiSearchViewController (){
    
    BLEServiceHandler *bleService;
    NSTimer *_timer;
    NSInteger _elapsedSeconds;
    BOOL startScan;
    
    NSMutableDictionary *wifiData;
    
}

@end

@implementation HomeHubWifiSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self prepareViewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

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

    bleService.delegate = self;
    
    if ([bleService isConnected] && bleService.conDevice != nil) {
        
        [self BLEConnected:_selectedModel];
    }
    else {
        
        [bleService connect:_selectedModel];
    }
    
}

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


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

- (void)prepareViewDidLoad {
    
 
    wifiData = [NSMutableDictionary new];
    
    //ble
    bleService = [BLEServiceHandler sharedManager];

    startScan = NO;

}

-(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 (startScan) {
            
            [bleService getWLanList:_elapsedSeconds%3];
        }

        
        if (_elapsedSeconds == 0) {
            
            if (wifiData.allKeys.count > 0) {
                
                [self moveHomeHubWifiSearchSuccess];
            }
            else {
                
                [self moveHomeHubWifiSearchFail];
            }

        }
    });
}


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


#pragma mark - ble service delegate
- (void)BLEConnected:(BTLEDeivceModel *)info {
    
    NSLog(@"home hub wifi search view connected!") ;

    startScan = YES ;
    [bleService scanWiFiList];
}

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


- (void)BLEWLanUpdateWithKey:(NSString *)kBLEChr result:(NSString *)result{

    BLEWLanListModel *response = [[BLEWLanListModel alloc] initWithString:result error:nil];
    
    if (response == nil) {
        
        return;
    }

    [wifiData setObject:response
                 forKey:kBLEChr];
    
    
    if (wifiData.allKeys.count == 3) {
        
        [self moveHomeHubWifiSearchSuccess];
    }
    
}


- (void)moveHomeHubWifiSearchSuccess {
 
    [self startLoading:NO];
    
    NSArray *allKeys = wifiData.allKeys ;
    NSMutableArray *wifiList = [NSMutableArray new] ;
    
    for (NSString *key in allKeys) {
        
        BLEWLanListModel *modelList = [wifiData objectForKey:key] ;
        
        for (BLEWLanModel *model in modelList.wlan) {
            
            [wifiList addObject:model];
        }
    }

    HomeHubWifiSearchSuccessViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubWifiSearchSuccessViewController" storyboardName:@"HomeHub"];
    vc.wifiList = wifiList;
    
    [self.navigationController pushViewController:vc animated:NO];
}


- (void)moveHomeHubWifiSearchFail {

    [self startLoading:NO];
    
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubWifiSearchFailViewController" storyboardName:@"HomeHub"];
    
    [self.navigationController pushViewController:vc animated:YES];
}


@end
