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

#import "HomeHubWifiPasswdInputViewController.h"
#import "HomeHubConnectWifiViewController.h"

@interface HomeHubWifiPasswdInputViewController ()<UITextFieldDelegate> {
    
    NSTimer *_timer;
    NSInteger _elapsedSeconds;
    
    BLEServiceHandler *bleService;
    
    BOOL updateSSID;
    BOOL updateBSSID;
    BOOL updateIPSet;
    BOOL updateIPAddr;
    
    
}

@end

@implementation HomeHubWifiPasswdInputViewController

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

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

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

- (void)initUI {
    
    _lblSSID.text = [NSString stringWithFormat:@"SSID : %@", _selectedWLanModel.ssid];
    _imgvLoading.hidden = YES;
    
}

- (void)prepareViewDidLoad {
    
    //ble
    bleService = [BLEServiceHandler sharedManager];
    
    updateSSID = updateBSSID = updateIPSet = updateIPAddr = NO;
    
}

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

-(void)startLoading:(BOOL)isStart {
    
    _imgvLoading.hidden = !isStart;
    
    if (isStart) {
        
        _elapsedSeconds = kMaxTimeOut*2;
        
        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) {

            //이떄 성공하지 않았으면 실패로 처리
            [self startLoading:NO];
            [[JDFacade facade] alertTitle:@"인터넷 연결 설정 실패" message:@"인터넷 연결 설정에 실패하였습니다."];

        }
    });
}

#pragma mark - User Event
- (IBAction)btnAgainTouched:(id)sender {
    
    BOOL find = NO;
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        
        if ([vc isKindOfClass:HomeHubConnectWifiViewController.class]) {
            
            find = YES;
            [self.navigationController popToViewController:vc animated:YES];
        }
    }
    
    if (!find) {
        
        UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubConnectWifiViewController" storyboardName:@"HomeHub"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (IBAction)btnConnectTouched:(id)sender {
    
    NSString *pass = _txtInputPasswd.text.trim;
    
    
    if (pass.length == 0) {
        
        return;
    }
    
    [self startLoading:YES];
    
    //1. write pass
    [bleService setWiFiPwd:pass];
    [self performSelector:@selector(BLESendEnableDHCP) withObject:nil afterDelay:1.0];
    
    updateSSID = updateBSSID = updateIPSet = updateIPAddr = NO;
}

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


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField.text.length > 0) {
        
        [self.view endEditing:YES];
        
    }
    
    return YES;
}

- (void)BLESendEnableDHCP {
    
    //2. set ip set arg chr
    [bleService enableDHCP];
    [bleService readAndNotifyCharacteristicUUID:kBLEChrStDHCPArg isNotify:NO];
    
}

#pragma mark - ble delegate
//enableDHCP
- (void)BLEWiFiDHCPUpdate:(id)data {
    
    //3. apply chr
    [bleService applyWiFiSettingInfo];
    
}


//kBLEChrRdConInfo
- (void)BLEWiFiConnectionUpdate:(CBCharacteristic *)info {
    
    NSString *value = [bleService hexStringValue:info] ;
    
    if (value.length > 0 &&
        EQUALS([value substringFromIndex:value.length-1], @"1")) {
        
        //5.
        [bleService readConnectionWiFiInfo];
    }
    else if (value.length > 0 &&
             EQUALS([value substringFromIndex:value.length-1], @"0")) {
        
        //실패
//        [self startLoading:NO];
//        [[JDFacade facade] alertTitle:@"인터넷 연결 설정 실패" message:@"인터넷 연결 설정에 실패하였습니다."];
    }
    
}

//readConnectionWiFiInfo
- (void)BLEWiFiConnectionInfoUpdateWithKey:(NSString *)kBLEChr
                                    result:(NSString *)result {
    
    NSLog(@"Connection Info Update!") ;
    
    if (EQUALS(kBLEChr, kBLEChrRdSSID)) {
        updateSSID = YES;
    }
    else if(EQUALS(kBLEChr, kBLEChrRdBSSID)) {
        updateBSSID = YES;
    }
    else if(EQUALS(kBLEChr, kBLEChrRnIpSet)) {
        updateIPSet = YES;
    }
    else if(EQUALS(kBLEChr, kBLEChrRnIpAddr)) {
        updateIPAddr = YES;
    }
    
    // 연결 확인 완료
    if (updateSSID && updateBSSID && updateIPSet && updateIPAddr) {
        
        [self startLoading:NO];
        
        UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubUpdateCompleteViewController" storyboardName:@"HomeHub"];
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}


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

@end
