const {
  DEFAULT_DEVICE_FILTER,
  getState: getHomeFeatureState,
  init: initHomeFeature,
  subscribeState: subscribeHomeState,
  ...homeService
} = require('../../features/home/service.js')
const {
  createPageToast
} = require('../../utils/page-toast.js')

Page({
  data: getHomeFeatureState(),

  noop() {},

  onLoad() {
    this.pageToast = createPageToast(this, this.data)
    initHomeFeature()
    this.unsubscribeHomeState = subscribeHomeState(() => this.data.deviceFilterMode, (nextState) => {
      this.setData(nextState)
      this.pageToast.showFromState(nextState)
    })
  },

  onShow() {
    if (this.pageToast) {
      this.pageToast.setActive(true)
    }
  },

  onHide() {
    if (this.pageToast) {
      this.pageToast.setActive(false)
    }
  },

  onUnload() {
    if (this.pageToast) {
      this.pageToast.destroy()
      this.pageToast = null
    }

    if (this.unsubscribeHomeState) {
      this.unsubscribeHomeState()
      this.unsubscribeHomeState = null
    }
  },

  startScan() {
    if (!this.data.canStartScan) return

    homeService.toggleScan(this.data.isDiscovering)
  },

  clearDevices() {
    if (!this.data.canClearDevices) return

    homeService.clearDevices()
  },

  onDeviceFilterTap(event) {
    const deviceFilterMode = event.currentTarget.dataset.filter || DEFAULT_DEVICE_FILTER

    this.setData(getHomeFeatureState(deviceFilterMode))
  },

  connectDevice(event) {
    homeService.connectDeviceById(event.currentTarget.dataset.deviceId)
  },

  disconnectDevice() {
    if (!this.data.canDisconnectDevice) return

    homeService.disconnectDevice()
  }
})
