//
//  CalendarManager.m
//  ReactNativeIos
//
//  Created by wuzhuoxuan on 2017/4/14.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import "Bluetooth.h"
#import "DeviceBluetooth.h"
#import <React/RCTConvert.h>

@interface Bluetooth ()
@property (nonatomic,strong)DeviceBluetooth *deviceBluet;
@property (nonatomic,strong)NSArray *list;
@end

@implementation Bluetooth
@synthesize bridge = _bridge;


RCT_EXPORT_MODULE();

// 初始化蓝牙设备
RCT_EXPORT_METHOD(create){
    NSLog(@"%@",self.deviceBluet);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(calendarEventReminderReceived:)name:@"Bluetooth.device.founded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(discount:)name:@"Bluetooth.discount" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoothOff:)name:@"Bluetooth.off" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scanningEquipment)name:@"Bluetooth.discovery.over" object:nil];
}

// 离开页面关闭扫描 删除通知
RCT_EXPORT_METHOD(destroy){
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSArray<NSString *> *)supportedEvents{
  return @[
           @"Bluetooth.device.founded",
           @"Bluetooth.discovery.over",
           @"Bluetooth.discount",
           @"Bluetooth.device.bonded",
           @"Bluetooth.off"];
}

RCT_REMAP_METHOD(discovery,
                  resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    [self.deviceBluet scanningEquipmentWithBluetoothDevice:^(NSString *success) {
      resolve(@"开始扫描");
    } andErrorDeviece:^(NSString *error) {
      NSError *err;
      reject(@"",error,err);
    }];
}

RCT_EXPORT_METHOD(toBluetooth){
  if([[UIDevice currentDevice] systemVersion].floatValue < 10.0){
    NSURL *url = [NSURL URLWithString:@"prefs:root=Bluetooth"];
    if([[UIApplication sharedApplication] canOpenURL:url]){
      [[UIApplication sharedApplication] openURL:url];
    }
  }else{
    NSURL *url = [NSURL URLWithString:@"App-Prefs:root=Bluetooth"];
    if ([[UIApplication sharedApplication]canOpenURL:url]) {
      [[UIApplication sharedApplication]openURL:url];
    }
  }
}

// 扫描到设备就发送消息
- (void)calendarEventReminderReceived:(NSNotification *)notification
{
  if(notification.object == nil){
      return;
  }
  dispatch_async(dispatch_get_main_queue(), ^{
    [self sendEventWithName:@"Bluetooth.device.founded" body:notification.object];
  });
}

// 关闭蓝牙扫描
RCT_EXPORT_METHOD(cancelDiscovery){
    [self.deviceBluet stopScanPeripheral];
}

// 蓝牙扫描结束
- (void)scanningEquipment{
  
  dispatch_async(dispatch_get_main_queue(), ^{
    // 蓝牙扫描结束通知
    [self sendEventWithName:@"Bluetooth.discovery.over" body:nil];
    
  });
}

// 蓝牙设备断开
- (void)discount:(NSNotification *)notification{
  
  dispatch_async(dispatch_get_main_queue(), ^{
    // 蓝牙设备断开通知
    [self sendEventWithName:@"Bluetooth.discount" body:notification.object];
  });
}

// 系统蓝牙关闭
- (void)bluetoothOff:(NSNotification *)notification{
  dispatch_async(dispatch_get_main_queue(), ^{
    // 系统蓝牙关闭通知
    [self sendEventWithName:@"Bluetooth.off" body:nil];
  });
}

// 连接蓝牙设备
RCT_EXPORT_METHOD(paired:(NSDictionary *)device callback:(RCTResponseSenderBlock)callback){
  NSLog(@"需要连接的设备==%@",device);
  if(device != nil){
    [self.deviceBluet connectTheDeviceWithPeripheral:device ConnectSuccess:^(NSString *success) {
      if(callback){
         callback(@[[NSNull null],success]);
      }
    } andConnectError:^(NSString *error) {
      if(callback){
        callback(@[error,[NSNull null]]);
      }
    }];
  }else{
    [self.deviceBluet connectTheDeviceWithPeripheral:nil ConnectSuccess:^(NSString *success) {
      if(callback){
        callback(@[[NSNull null],success]);
      }
    } andConnectError:^(NSString *error) {
      if(callback){
        callback(@[error,[NSNull null]]);
      }
    }];
  }
}

//断开连接
RCT_EXPORT_METHOD(disconnect:(NSString *)peripheral){
  [self.deviceBluet didDisconnectPeripheral:@{@"identifier":peripheral}];
}

- (DeviceBluetooth *)deviceBluet{
  if(_deviceBluet == nil){
    _deviceBluet = [DeviceBluetooth sharedInstance];
  }
  return _deviceBluet;
}

- (void)dealloc{
  [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
