//
//  lemon_react_native.m
//  lemon-react-native
//
//  Created by rrd on 2017/6/28.
//  Copyright © 2017年 we. All rights reserved.
//

#import "LemonReactNative.h"
#import "QRCodeViewController.h"
#import "LemonVolume.h"

@implementation LemonReactNative

- (void) setupLemon:(UIViewController *)vc openCallback:(openUrlCallback)openCallback rnCall:(callback)rnCall qrCall:(callback)qrCall{
    //初始化当前实用的vc
    _currVC = vc;
    _rnOptionCallback = rnCall;
    _qrOptionCallback = qrCall;
    _openCallback = openCallback;
    
    //添加debug监听选项
    [self addDebug];
}

- (void) destoryLemon{
    _currVC = nil;
    _rnOptionCallback = nil;
    _qrOptionCallback = nil;
    _openCallback = nil;
    
    [self removeDebug];
}

-(void) addDebug{
    
    __weak typeof(self) weakSelf = self;
    
    _buttonStealer = [[LemonVolume alloc] init];
    
    self.buttonStealer.upBlock = ^{
        UInt64 currTime = [[NSDate date] timeIntervalSince1970]*1000;
        if(weakSelf.prevListenTime){
            if(currTime - _prevListenTime < 300){
                //当两次按键的时间差<0.3s的时候触发，选项操作
                [weakSelf showDebugOption:weakSelf.currVC rnCall:weakSelf.rnOptionCallback qrCall:weakSelf.qrOptionCallback];
            }
        }
        _prevListenTime = currTime;
    };
    self.buttonStealer.downBlock = nil;
    
    [self.buttonStealer startStealingVolumeEvents];
}


-(void) removeDebug{
    _buttonStealer = nil;
}

//添加一个rn点击回调
- (void) showDebugOption:(UIViewController *)vc rnCall:(callback)rnCall qrCall:(callback)qrCall{
    //init option
    UIAlertController* debugOption = [self setUpDebugOption:vc rnCall:rnCall qrCall:qrCall];
    dispatch_async(dispatch_get_main_queue(), ^{
        [vc presentViewController:debugOption animated:YES completion:nil];
    });
}

//创建调试选项
-(UIAlertController *) createDebugOption{
    UIAlertController* debugOption = [UIAlertController alertControllerWithTitle:@"RN调试选项" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    return debugOption;
}

//添加调试选项
-(void) addDebugAction:(NSString *)title style:(UIAlertActionStyle)style debugOption:(UIAlertController *)debugOption handler:(callback)handler{
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:title style:style handler:^(UIAlertAction * uaa) {
        if(handler){
            handler();
        }
    }];
    
    [debugOption addAction:action];
    
}


-(UIAlertController *) setUpDebugOption:(UIViewController *)vc rnCall:(callback)rnCall qrCall:(callback)qrCall{
    
    __weak typeof(self) weakSelf = self;
    UIAlertController* debugOption =  [self createDebugOption];
    
    [self addDebugAction:@"扫描二维码" style:UIAlertActionStyleDefault debugOption:debugOption handler:^{
        [weakSelf openQRVC:vc];//使用weak 防止内存泄露
        if(qrCall){
            qrCall();
        }
    }];
    
    [self addDebugAction:@"ReactNative" style:UIAlertActionStyleDefault debugOption:debugOption  handler:^{
        if(rnCall){
            rnCall();
        }
    }];
    
    [self addDebugAction:@"服务配置" style:UIAlertActionStyleDefault debugOption:debugOption  handler:^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"地址和端口" message:@"修改后需要重启App" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
            textField.placeholder = @"127.0.0.1:8081";
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            UITextField *addr = alertController.textFields.firstObject;
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            if(addr.text.length == 0){
                addr.text = @"127.0.0.1:8081";
            }
            [defaults setObject:addr.text forKey:@"__react_native_host_port"];
            [defaults synchronize];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [vc presentViewController:alertController animated:YES completion:nil];
    }];
    
    [self addDebugAction:@"关闭" style:UIAlertActionStyleCancel debugOption:debugOption handler:nil];
    
    
    return debugOption;
}

//打开qrcode viewcontroller
-(void) openQRVC : (UIViewController*) vc{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"QRCode" bundle:[NSBundle bundleForClass:LemonReactNative.self]];
    QRCodeViewController *qrvc = (QRCodeViewController *)[storyboard instantiateViewControllerWithIdentifier:@"qrcode"];
    qrvc.openPressCallback = ^(NSString *url){
        NSLog(@"扫描结果: %@",url);
        if(self.openCallback){
            self.openCallback(url);
        }
    };
    dispatch_async(dispatch_get_main_queue(), ^{
        [vc presentViewController:qrvc animated:YES completion:nil];
    });
    
}

-(void) addOpenUrlCallback:(openUrlCallback)openCallback{
    _openCallback = openCallback;
}

+ (NSString*) getDebugHost{
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString* str = [defaults objectForKey:@"__react_native_host_port"];
    if(str.length == 0){
        return @"127.0.0.1:8081";
    }
    return str;
}


@end
