const Manager = require('./manager');
const BtParse = require('../../devices/bluetooth/bt_parse');

/// MW-X4 (BZK)
class BleUtil {
  static _instance = new BleUtil();

  static getInstance() {
    return BleUtil._instance;
  }

  constructor() {
    var that = this;
    that.manager = new Manager();
  }

  ///获取比较的数据
  getCompareList() {
    var that = this;
    return that.manager.getCompareList();
  }

  getDissmissDevice() {
    var that = this;
    return that.manager.getDissmissDevice();
  }

  getCallBackConnect() {
    var that = this;
    return that.manager.getCallBackConnect();
  }

  ///初始化蓝牙适配器
  initBluetoothAdapter() {
    var that = this;
    that.manager.initBlueAdapter();
  }

  ///获取蓝牙设备 connect:true，去连接，false,去对比
  listenBlueDevices() {
    var that = this;
    that.manager.listenBlueDevices();
  }

  ///搜索蓝牙设备
  startScan(connectWillDevice, boolean, callBackConnect) {
    var that = this;
    that.manager.startScan(
      connectWillDevice,
      boolean,
      callBackConnect,
    );
  }

  ///停止搜索蓝牙设备
  async stopScan() {
    var that = this;
    await that.manager.stopScan();
  }

  ///开始连接设备
  async startConnect(device, onChanged) {
    var that = this;
    await that.stopScan();
    // await that.disconnect(device);

    var res = await that.manager.startConnect(device);
    if (!res) {
      that.disconnect(device);
      onChanged(false);
      return;
    }

    const strings = require('./../../utils/strings');
    var services = await that.manager.getNotifyServices(device);
    console.log("gadsfasdfadfaf===333==" + JSON.stringify(services));
    if (strings.isEmpty(services)) {
      that.disconnect(device);
      onChanged(false);
      return;
    }

    var serviceId = serviceId = services[0].uuid;
    for (let i = 0; i < services.length; i++) {
      if (services[i].uuid.toUpperCase().indexOf("FFE5") != -1 ||
        services[i].uuid.toUpperCase().indexOf("1111") != -1
      ) {
        serviceId = services[i].uuid;
        break;
      }
    }

    var isRead = false;
    var isWrited = false;
    that.manager.setWriteServiceId(serviceId);
    that.manager.getCharacteristics(device, function () {
        that.disconnect(device);
        onChanged(false);
      }, function (notifyCharaterId) {
        ///监听特征值变化
        var isTrue = that.manager.monitorCharacteristicValueChange(device, serviceId, notifyCharaterId);
        if (!isTrue) {
          onChanged(false);
          return;
        }

        ///数据接收
        that.manager.onBLECharacteristicValueChange(function (value) {
          BtParse.parseTLV(value);
        });
        isRead = true;
        if (isWrited) {
          console.log("gadsfasdfadfaf===7777==");
          setTimeout(() => {
            onChanged(true);
          }, 300);
        }
      },
      async function () {
          isWrited = true;
          if (isRead) {
            console.log("gadsfasdfadfaf===8888==");
            setTimeout(() => {
              onChanged(true);
            }, 300);
          }
        },
        function () {
          onChanged(false);
          return;
        });
  }

  ///发送数据
  async sendData(device, wifiName, pwd) {
    var that = this;
    var text = that.sendWiFiInfo(wifiName, pwd);
    console.log("gadsfasdfadfaf===888==" + text);
    var isTrue = await that.manager.sendData(device, text);
    console.log("gadsfasdfadfaf===999==" + isTrue);
    ///发送数据成功
    if (isTrue) {

    }
  }

  sendWiFiInfo(wifiName, pwd) {
    const hex_util = require('../hex_util');
    let result = [];

    // 字母*6 +
    let wifiList = hex_util.string2ListInt(wifiName);

    // 数字*3 +
    let pwdList = hex_util.string2ListInt(pwd);

    // 16进制
    result.push(0x22);
    result.push(parseInt(hex_util.int2Hex(wifiList.length + pwdList.length + 6), 16));

    // 账号
    result.push(0x33);
    result.push(parseInt(hex_util.int2Hex(wifiList.length), 16));

    let p = result[3] + 4;
    let j = 0;
    for (let i = 4; i < p; i++) {
      result.splice(i, 0, wifiList[j++]);
    }

    // 密码
    result.splice(p, 0, 0x44);
    result.splice(++p, 0, parseInt(hex_util.int2Hex(pwdList.length), 16));
    p++;
    j = 0;
    for (let i = p; i < p + pwdList.length; i++) {
      result.splice(i, 0, pwdList[j++]);
    }
    ///[34, 22, 51, 5, 109, 117, 122, 101, 110, 68, 11, 109, 117, 122, 101, 110, 111, 102, 102, 105, 99, 101]
    console.log("发送wifi账号密码：", result.toString());
    return result.toString();
  }

  ///断开设备连接
  async disconnect(device) {
    var that = this;
    await that.manager.disconnect(device);
  }
}
module.exports = {
  BleUtil
}