//
//  bluetooth.m
//  testDemo2
//
//  Created by wuzhuoxuan on 2017/4/14.
//  Copyright © 2017年 wuzhuoxuan. All rights reserved.
//

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


static DeviceBluetooth *deviceBluetooth = nil;

@implementation DeviceBluetooth

+ (DeviceBluetooth *)sharedInstance{
    @synchronized(self)//线程加锁
    {
        static dispatch_once_t onceToken ;
        dispatch_once(&onceToken, ^{
            deviceBluetooth = [[super allocWithZone:NULL] init];
            deviceBluetooth.centralManager = [[CBCentralManager alloc]initWithDelegate:deviceBluetooth queue:nil];
        }) ;
    }
    return deviceBluetooth;
}

+ (id) allocWithZone:(struct _NSZone *)zone{
    return [DeviceBluetooth sharedInstance] ;
}

- (id) copyWithZone:(struct _NSZone *)zone{
    return [DeviceBluetooth sharedInstance] ;
}

/**
 扫描的方法
 
 @param bluetoothDevice      成功
 @param errorDeviece         失败
 */
- (void)scanningEquipmentWithBluetoothDevice:(BluetoothDevice)bluetoothDevice andErrorDeviece:(ErrorBluetoothDeviece)errorDeviece{
  if(self.centralManager.state != CBCentralManagerStatePoweredOn){
    if(errorDeviece){
      errorDeviece(@"请开启蓝牙");
      return;
    }
  }
  
  self.bluetoothDevice = ^(NSString *success) {
    if(bluetoothDevice){
      bluetoothDevice(success);
    }
  };
  
  self.errorBluetoothDeviece = ^(NSString *error){
    if(errorDeviece){
      errorDeviece(error);
    }
  };
    // 查找蓝牙设备
    [self FindClick];
}
/**
 连接的方法  成功 失败
 @param connectSuccess       连接成功
 @param connectError         连接失败
 */
- (void)connectTheDeviceWithPeripheral:(NSDictionary *)peripheral ConnectSuccess:(ConnectSuccess)connectSuccess andConnectError:(ConnectError)connectError{
  if(self.centralManager.state != CBCentralManagerStatePoweredOn){
    if(connectError){
      connectError(@"请开启蓝牙");
      return;
    }
  }
  if(peripheral == nil){
    self.deviceName = @"";
  }else{
    self.deviceName = peripheral[@"identifier"];
  }
  self.connectSuccess = ^(NSString *center) {
    if(connectSuccess){
      connectSuccess(center);
    }
  };
  self.connectError = ^(NSString *error) {
    if(connectError){
      connectError(error);
    }
  };
  for(int i=0; i<self.deviceList.count; i++) {
    CBPeripheral *per = self.deviceList[i];
    if([self.deviceName isEqualToString:[per.identifier UUIDString]]){
      if(per.state != CBPeripheralStateConnected){
        [self connectionClick:per];
        return;
      }
    }
  }
  self.connectError(@"连接设备失败");
}


/**
 *  断开连接设备
 */
- (void)didDisconnectPeripheral:(NSDictionary *)peripheral{
  for(int i=0; i<self.deviceList.count; i++) {
    CBPeripheral *per = self.deviceList[i];
    if([self.deviceName isEqualToString:[per.identifier UUIDString]]){
      [self.centralManager stopScan];
      [self.centralManager cancelPeripheralConnection:per];
    }
  }
  if (self.selectedPeripheral.state==CBPeripheralStateConnected)
    [self.centralManager cancelPeripheralConnection:self.selectedPeripheral];
}


// 查找蓝牙设备
- (void)FindClick{
    //清空当前设备列表
    self.deviceList = nil;
    self.nameList = nil;
    [self.centralManager scanForPeripheralsWithServices:nil options:nil];
    [self Time];
    if(self.bluetoothDevice){
        self.bluetoothDevice(@"开始扫描");
    }
    
}

- (void)Time{
      __block int timeOut = 10;
      
      dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
      
      dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
      
      dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
      
      dispatch_source_set_event_handler(_timer, ^{
        if(timeOut < 0){ //倒计时结束，关闭
          dispatch_source_cancel(_timer);
          dispatch_async(dispatch_get_main_queue(), ^{
            //设置界面的按钮显示 根据自己需求设置

            [self stopScanPeripheral];
          });
        }else{
          //            int seconds = timeOut % 60;
            timeOut--;
        }
      });
      dispatch_resume(_timer);
}


- (void) stopScanPeripheral{
    [self.centralManager stopScan];
    NSLog(@"stop scan");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Bluetooth.discovery.over" object:nil];
}



// 连接
- (void)connectionClick:(CBPeripheral *)device{
    if(device.state==CBPeripheralStateConnected){
        [self.centralManager cancelPeripheralConnection:device];
        NSLog(@"已经连接");
    }else{
        NSLog(@"stop scan");
        self.selectedPeripheral = device;
        [self.centralManager connectPeripheral:device options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : @YES}];
    }
}



#pragma mark ==================连接打印机===============================
#pragma  mark -- CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString * state = nil;
    switch ([central state])
    {
        case CBCentralManagerStateUnsupported:
            state = @"The platform/hardware doesn't support Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnauthorized:
            state = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStatePoweredOff:
            state = @"Bluetooth is currently powered off.";
            break;
        case CBCentralManagerStatePoweredOn:
            state = @"work";
            break;
        case CBCentralManagerStateUnknown:
        default:
            ;
    }
    if(central.state == CBCentralManagerStatePoweredOff){
      [[NSNotificationCenter defaultCenter] postNotificationName:@"Bluetooth.off" object:nil];
      NSLog(@"设备蓝牙已经关闭");
    }
    NSLog(@"Central manager state: %@", state);
    
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if (peripheral)
    {
            NSLog(@"foundDevice.name[%@],RSSI[%ld]\n",peripheral.name,(long)peripheral.state);
            NSString *name = peripheral.name;
            int bondState = -1;
      
            if(peripheral.state == CBPeripheralStateConnected){
                bondState = 0;
            }
            if(name){
              NSMutableDictionary *periphDict = [NSMutableDictionary dictionary];
              [periphDict setObject:[NSString stringWithFormat:@"%@",[peripheral.identifier UUIDString]] forKey:@"address"];
              [periphDict setObject:peripheral.name forKey:@"name"];
              [periphDict setObject:@(bondState) forKey:@"bondState"];
              for (int i = 0; i<self.nameList.count; i++) {
                NSDictionary *dict = self.nameList[i];
                if([periphDict[@"address"] isEqualToString:dict[@"address"]]){
                  NSLog(@"periphDict=%@ /n \n dict=%@",periphDict[@"address"] ,dict[@"address"]);
                  
                  return;
                }
              }
                [self.nameList addObject:periphDict];
                [self.deviceList addObject:peripheral];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Bluetooth.device.founded" object:periphDict];
            }
    }
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"has connected");
  if(self.connectSuccess){
    self.connectSuccess(@"设备连接成功");
  }
    
}

// 断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Peripheral Disconnected");
    NSMutableDictionary *periphDict = [NSMutableDictionary dictionary];
    [periphDict setObject:[NSString stringWithFormat:@"%@",[peripheral.identifier UUIDString]] forKey:@"address"];
    [periphDict setObject:peripheral.name forKey:@"name"];
    [periphDict setObject:@(-1) forKey:@"bondState"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Bluetooth.discount" object:periphDict];
    
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //此时连接发生错误
    NSLog(@"connected periphheral failed");
  if(self.connectError){
    self.connectError(@"设备连接失败");

  }
}

- (NSMutableArray *)deviceList{
  
    if(_deviceList == nil){
      
        _deviceList = [NSMutableArray array];
    }
    return _deviceList;
}

- (NSMutableArray *)nameList{
  
  if(_nameList == nil){
   
     _nameList = [NSMutableArray array];
  }
  return _nameList;
}

- (NSString *)deviceName{
  
  if(_deviceName == nil){
    _deviceName = [NSString string];
  }
  return _deviceName;
}

@end
