const transport = require('../../transport/ble-core.js')
const themeService = require('../../store/theme-store.js')

const DEFAULT_DEVICE_FILTER = 'all'
const DEVICE_FILTER_OPTIONS = [
  { key: 'all', label: '全部' },
  { key: 'target', label: '目标' }
]

let initScheduled = false

function isTargetDevice(device) {
  return !!(device && (device.isTargetDevice || device.isTargetAdvertised))
}

function filterDevices(devices, filterMode) {
  if (filterMode === 'target') return devices.filter(isTargetDevice)

  return devices
}

function getHomePageState(
  transportState = transport.getState(),
  deviceFilterMode = DEFAULT_DEVICE_FILTER,
  themeState = themeService.getState()
) {
  const { connectedDevice } = transportState
  const filteredDevices = filterDevices(transportState.devices, deviceFilterMode)
  const allDeviceCount = transportState.devices.length
  const filteredDeviceCount = filteredDevices.length
  const connectionStatusText = connectedDevice
    ? '已连接'
    : (transportState.isConnecting ? '连接中' : '未连接')

  return {
    ...transportState,
    ...themeState,
    allDeviceCount,
    canClearDevices: !!allDeviceCount && !transportState.isConnecting,
    canDisconnectDevice: !!connectedDevice,
    canStartScan: !transportState.isConnecting,
    connectionCharacteristicText: connectedDevice ? transportState.characteristicText : '--',
    connectionDeviceId: connectedDevice ? connectedDevice.deviceId : '--',
    connectionName: connectedDevice ? connectedDevice.displayName : '',
    connectionServiceCount: connectedDevice ? transportState.connectedServiceCount : '--',
    connectionSignalText: connectedDevice
      ? (transportState.signalText || connectedDevice.signalText || '--')
      : '--',
    connectionStatusText,
    devices: filteredDevices,
    deviceCountText: allDeviceCount
      ? (deviceFilterMode === 'target' ? `(${filteredDeviceCount}/${allDeviceCount})` : `(${allDeviceCount})`)
      : '',
    deviceFilterMode,
    deviceFilterOptions: DEVICE_FILTER_OPTIONS,
    emptyDeviceText: allDeviceCount && deviceFilterMode === 'target'
      ? '当前扫描结果中没有广播目标 UUID 的设备，可切回全部后连接确认特征值。'
      : '请确认设备已上电并处于可广播或配网状态。',
    emptyDeviceTitle: allDeviceCount && deviceFilterMode === 'target'
      ? '没有匹配目标特征的设备'
      : '还没有发现设备',
    scanButtonText: transportState.isDiscovering ? '停止' : '扫描',
    showDeviceSection: true
  }
}

function deferStartupWork(task) {
  if (typeof task !== 'function') return

  if (typeof setTimeout === 'function') {
    setTimeout(task, 120)
    return
  }

  task()
}

function init() {
  if (initScheduled) return

  initScheduled = true
  deferStartupWork(() => {
    try {
      transport.init()
      themeService.init()
    } catch (error) {}
  })
}

function getState(deviceFilterMode = DEFAULT_DEVICE_FILTER) {
  return getHomePageState(
    transport.getState(),
    deviceFilterMode,
    themeService.getState()
  )
}

function subscribeState(getDeviceFilterMode, subscriber) {
  if (typeof subscriber !== 'function') return () => {}

  const getFilterMode = typeof getDeviceFilterMode === 'function'
    ? getDeviceFilterMode
    : () => DEFAULT_DEVICE_FILTER
  const emit = () => subscriber(getState(getFilterMode()))

  const unsubscribers = [
    transport.subscribe(emit),
    themeService.subscribe(emit)
  ]

  return () => {
    unsubscribers.forEach((unsubscribe) => {
      if (typeof unsubscribe === 'function') unsubscribe()
    })
  }
}

function toggleScan(isDiscovering) {
  return isDiscovering ? transport.stopScan() : transport.startScan()
}

module.exports = {
  DEFAULT_DEVICE_FILTER,
  DEVICE_FILTER_OPTIONS,
  clearDevices: transport.clearDevices,
  connectDeviceById: transport.connectDeviceById,
  disconnectDevice: transport.disconnectDevice,
  filterDevices,
  getHomePageState,
  getState,
  init,
  isTargetDevice,
  subscribeState,
  toggleScan
}
