const transport = require('../../transport/ble-core.js')
const themeService = require('../../store/theme-store.js')
const {
  DEFAULT_DEVICE_FILTER,
  getHomePageState
} = require('./view-model.js')

let initScheduled = false

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,
  clearDevices: transport.clearDevices,
  connectDeviceById: transport.connectDeviceById,
  disconnectDevice: transport.disconnectDevice,
  getState,
  init,
  subscribeState,
  toggleScan
}
