'use strict'
!(function(require, directRequire) {
  async function a() {
    return new Promise(a => {
      o.getAdapterState(function(b) {
        const c = b.available,
          d = b.powered,
          e = b.discovering
        ;(q = { available: c, powered: d, discovering: e }), a(q)
      })
    })
  }
  async function b() {
    return (
      o.onDeviceAdded.addListener(c),
      o.onDeviceChanged.addListener(d),
      o.onAdapterStateChanged.addListener(A),
      p.onCharacteristicValueChanged.addListener(e),
      (r = !0),
      await a()
    )
  }
  function c(a) {
    if (h(a) && q.discovering && r && (t || !w[a.address])) {
      const b = {
        name: a.name,
        deviceId: a.address,
        RSSI: a.inquiryRssi,
        advertisServiceUUIDs: a.uuids
      }
      ;(w[b.deviceId] = b), u ? (v[b.deviceId] = b) : i([b])
    }
  }
  function d(a) {
    if (x.hasOwnProperty(a.address) && r && x[a.address] !== a.connected) {
      var b = { connected: a.connected, deviceId: a.address }
      ;(x[a.address] = a.connected),
        l.triggerOnEvent({ eventName: 'onBLEConnectionStateChanged', data: b })
    }
  }
  function e(a) {
    if (r) {
      const b = a.instanceId || a.uuid,
        c = y[b],
        d = {
          value: m(a.value),
          deviceId: c.deviceId,
          serviceId: c.serviceId,
          characteristicId: b
        }
      l.triggerOnEvent({ eventName: 'onBLECharacteristicValueChange', data: d })
    }
  }
  async function f() {
    for (let a in y)
      y[a] &&
        p.stopCharacteristicNotifications(a, function() {
          y[a] = !1
        })
    for (let a in x)
      x[a] &&
        p.disconnect(a, function() {
          x[a] = !1
        })
    return (
      q.discovering && j({}, function() {}),
      (q = { available: !1, powered: !1, discovering: !1 }),
      (r = !1),
      q
    )
  }
  async function g() {
    return (
      o.onDeviceAdded.removeListener(c),
      o.onDeviceChanged.removeListener(d),
      o.onAdapterStateChanged.removeListener(A),
      p.onCharacteristicValueChanged.removeListener(e),
      await f()
    )
  }
  function h(a) {
    if (!s.length) return !0
    const b = a.uuids,
      c = s.some(function(a) {
        return b.some(function(b) {
          return !!(0 <= b.toUpperCase().indexOf(a.toUpperCase()))
        })
      })
    return c
  }
  function i(a) {
    apppserviceMesager.triggerOnEvent({
      eventName: 'onBluetoothDeviceFound',
      data: a
    })
  }
  async function j(a, b) {
    return new Promise(a => {
      o.stopDiscovery(
        z(b, function(c) {
          c
            ? a({ errMsg: `${b.api}:fail ${c.message}` })
            : ((q.discovering = !1),
              a({ errMsg: `${b.api}:ok`, isDiscovering: !1 }),
              u && (clearInterval(u), (u = null)),
              (t = !1),
              (v = {}),
              (w = {}))
        })
      )
    })
  }
  const k = require('./logger.js'),
    l = require('./a1dd553cc059d528bb0ef56afed53968.js'),
    {
      arrayBufferToBase64: m,
      base64ToArrayBuffer: n
    } = require('./db24ed4552e3b37097723f3b900374cf.js'),
    o = chrome.bluetooth,
    p = chrome.bluetoothLowEnergy || {}
  let q = { available: !1, powered: !1, discovering: !1 },
    r = !1,
    s = [],
    t = !1,
    u = null,
    v = {},
    w = {},
    x = {},
    y = {}
  const z = function(a, b) {
      return function() {
        if (chrome.runtime.lastError) b(chrome.runtime.lastError)
        else {
          let a = Array.from(arguments)
          b.apply(null, [null].concat(a))
        }
      }
    },
    A = z('', function(a, b) {
      if (!a) {
        const a = b.available,
          c = b.powered,
          d = b.discovering
        ;(q = { available: a, powered: c, discovering: d }),
          r &&
            webviewActions.postMessageToAS({
              eventName: 'onBluetoothAdapterStateChange',
              type: 'ON_BLUETOOTH_EVENT',
              data: q
            })
      }
    })
  var B = {
    openBluetoothAdapter: async function(a, c) {
      if (r) return { errMsg: `${c.api}:fail already opened` }
      let d = await b()
      return d.available && d.powered
        ? { errMsg: `${c.api}:ok` }
        : { errMsg: `${c.api}:fail bluetooth adapter unavailable` }
    },
    closeBluetoothAdapter: async function(a, b) {
      return r
        ? (await g(), { errMsg: `${b.api}:ok` })
        : { errMsg: `${b.api}:fail already closed` }
    },
    getBluetoothAdapterState: async function(a, b) {
      return new Promise(a => {
        o.getAdapterState(
          z(b, function(c, d) {
            c
              ? a({ errMsg: `${b.api}:fail ${c.message}` })
              : ((q = {
                  available: d.available,
                  powered: d.powered,
                  discovering: d.discovering
                }),
                a({ errMsg: `${b.api}:ok`, adapterState: q }))
          })
        )
      })
    },
    startBluetoothDevicesDiscovery: async function(a, b) {
      if (q.discovering)
        return { errMsg: `${b.api}:fail already discovering devices` }
      ;(s = b.args.services || []), (t = b.args.allowDuplicatesKey || !1)
      const d = b.args.interval || 0
      return new Promise(a => {
        o.getDevices(function(e) {
          o.startDiscovery(
            z(b, function(f) {
              if (f) a({ errMsg: `${b.api}:fail ${f.message}` })
              else if (
                ((q.discovering = !0),
                a({ errMsg: `${b.api}:ok`, isDiscovering: !0 }),
                0 === d)
              )
                e.forEach(function(a) {
                  c(a)
                })
              else {
                const a = e.map(function(a) {
                  const b = {
                    name: a.name,
                    deviceId: a.address,
                    RSSI: a.inquiryRssi,
                    advertisServiceUUIDs: a.uuids
                  }
                  return (w[b.deviceId] = b), b
                })
                i(a),
                  (u = setInterval(function() {
                    const a = Object.keys(v)
                    if (0 !== a.length) {
                      const b = a.reduce(function(a, b) {
                        return a.push(v[b]), a
                      }, [])
                      i(b), (v = {})
                    }
                  }, d))
              }
            })
          )
        })
      })
    },
    stopBluetoothDevicesDiscovery: j,
    getBluetoothDevices: async function(a) {
      return new Promise(b => {
        o.getDevices(
          z(a, function(c, d) {
            if (c) b({ errMsg: `${a.api}:fail ${c.message}` })
            else {
              d = d || []
              let c = d.filter(h).map(function(a) {
                return {
                  name: a.name,
                  deviceId: a.address,
                  RSSI: a.inquiryRssi,
                  advertisServiceUUIDs: a.uuids
                }
              })
              b({ errMsg: `${a.api}:ok`, devices: c })
            }
          })
        )
      })
    },
    getConnectedBluetoothDevices: async function(a, b) {
      return new Promise(a => {
        o.getDevices(
          z(b, function(c, d) {
            if (c) callback({ errMsg: `${b.api}:fail ${c.message}` })
            else {
              d = d || []
              const c = b.args.services,
                e = d.filter(function(a) {
                  return a.connected
                })
              Promise.all(
                e.map(function(a) {
                  return new Promise(function(b) {
                    p.getServices(a.address, function(a) {
                      const d = a.some(function(a) {
                        return (
                          a.isPrimary &&
                          c.some(function(b) {
                            return b === a.uuid
                          })
                        )
                      })
                      b(d)
                    })
                  })
                })
              ).then(function(c) {
                const d = e.reduce(function(a, b, d) {
                  return (
                    c[d] &&
                      a.push({
                        name: b.name,
                        deviceId: b.address,
                        RSSI: b.inquiryRssi
                      }),
                    a
                  )
                }, [])
                a({ errMsg: `${b.api}:ok`, devices: d })
              })
            }
          })
        )
      })
    },
    createBLEConnection: async function(a, b) {
      let c = b.args.deviceId
      return (
        (x[c] = !1),
        new Promise(a => {
          p.connect(
            c,
            z(b, function(c) {
              c
                ? a({ errMsg: `${b.api}:fail ${c.message}` })
                : a({ errMsg: `${b.api}:ok` })
            })
          )
        })
      )
    },
    closeBLEConnection: async function(a, b) {
      return new Promise(a => {
        let c = b.args.deviceId
        p.disconnect(
          c,
          z(b, function(d) {
            d
              ? a({ errMsg: `${b.api}:fail ${d.message}` })
              : ((x[c] = !1), a({ errMsg: `${b.api}:ok` }))
          })
        )
      })
    },
    getBLEDeviceServices: async function(a, b) {
      return new Promise(a => {
        let c = b.args.deviceId
        p.getServices(
          c,
          z(b, function(c, d) {
            if (c) a({ errMsg: `${b.api}:fail ${c.message}` })
            else {
              d = d || []
              let c = d.map(function(a) {
                return {
                  uuid: a.instanceId ? a.instanceId : a.uuid,
                  isPrimary: a.isPrimary
                }
              })
              a({ errMsg: `${b.api}:ok`, services: c })
            }
          })
        )
      })
    },
    getBLEDeviceCharacteristics: async function(a) {
      return new Promise(b => {
        let c = a.args.serviceId
        p.getCharacteristics(
          c,
          z(a, function(c, d) {
            if (c) b({ errMsg: `${a.api}:fail ${c.message}` })
            else {
              const c = ['read', 'write', 'notify', 'indicate']
              d = d || []
              let e = d.map(function(a) {
                return {
                  uuid: a.instanceId || a.uuid,
                  properties: a.properties.reduce(function(a, b) {
                    return (a[b] = 0 <= c.indexOf(b)), a
                  }, {})
                }
              })
              b({ errMsg: `${a.api}:ok`, characteristics: e })
            }
          })
        )
      })
    },
    readBLECharacteristicValue: async function(a) {
      return new Promise(b => {
        const c = a.args.deviceId,
          d = a.args.serviceId,
          f = a.args.characteristicId
        p.readCharacteristicValue(
          f,
          z(a, function(f, g) {
            f
              ? b({ errMsg: `${a.api}:fail ${f.message}` })
              : ((g.deviceId = c),
                (g.serviceId = d),
                e(g),
                b({ errMsg: `${a.api}:ok` }))
          })
        )
      })
    },
    writeBLECharacteristicValue: async function(a) {
      return new Promise(b => {
        let c = a.args.characteristicId,
          d = n(a.args.value)
        p.writeCharacteristicValue(
          c,
          d,
          z(a, function(c) {
            c
              ? b({ errMsg: `${a.api}:fail ${c.message}` })
              : b({ errMsg: `${a.api}:ok` })
          })
        )
      })
    },
    notifyBLECharacteristicValueChanged: async function(a) {
      return new Promise(b => {
        const c = a.args.deviceId,
          d = a.args.serviceId,
          e = a.args.characteristicId,
          f = a.args.state,
          g = z(a, function(c) {
            c
              ? b({ errMsg: `${a.api}:fail ${c.message}` })
              : b({ errMsg: `${a.api}:ok` })
          })
        if (f) {
          if (y[e]) return
          p.startCharacteristicNotifications(e, g),
            (y[e] = { deviceId: c, serviceId: d })
        } else {
          if (!y[e]) return
          p.stopCharacteristicNotifications(e, g), (y[e] = null)
        }
      })
    }
  }
  const C = 'darwin' === process.platform
  Object.getOwnPropertyNames(B).forEach(function(a) {
    const b = B[a]
    B[a] = async function(a, c) {
      if (!C)
        return {
          errMsg: `${c.api}:fail 目前蓝牙调试功能暂不支持 Mac 以外的平台`
        }
      return r || 'openBluetoothAdapter' === c.api
        ? await b.apply(B, arguments)
        : {
            errMsg: `${
              c.api
            }:fail 请先调用 wx.openBluetoothAdapter 接口进行初始化操作`
          }
    }
  }),
    (module.exports = B)
})(require('lazyload'), require)
