const settingsService = require('../../store/settings-store.js')
const themeService = require('../../store/theme-store.js')
const transport = require('../../transport/ble-core.js')
const bootloaderService = require('../bootloader/service.js')
const {
  toolNavigation
} = require('../tools/index.js')
const protocolImplementation = require('./protocol-implementation.js')

function getSettingsPageState(
  settingsState = settingsService.getState(),
  themeState = themeService.getState(),
  transportState = transport.getState(),
  bootloaderState = bootloaderService.getState()
) {
  const nightModeEnabledSwitch = settingsState.nightModeFollowSystem
    ? themeState.themeMode === 'dark'
    : settingsState.nightModeEnabled
  const protocolMode = settingsState.protocolMode || settingsService.PROTOCOL_MODE.STORAGE_ACCESS
  const protocolOptions = settingsService.PROTOCOL_OPTIONS
  const protocolIndex = Math.max(0, protocolOptions.findIndex((option) => (
    option.key === protocolMode
  )))
  const protocol = protocolOptions[protocolIndex] || protocolOptions[0]
  const isNoProtocol = settingsService.isNoProtocol(protocol.key)
  const isModbusProtocol = settingsService.isModbusProtocol(protocol.key)
  const isStorageAccessProtocol = settingsService.isStorageAccessProtocol(protocol.key)

  return {
    ...settingsState,
    ...themeState,
    ...bootloaderState,
    connectedDevice: transportState.connectedDevice,
    isNoProtocol,
    isModbusProtocol,
    isStorageAccessProtocol,
    nightModeEnabledSwitch,
    statusPollMaxInterval: settingsService.STATUS_POLL_MAX_INTERVAL,
    statusPollMinInterval: settingsService.STATUS_POLL_MIN_INTERVAL,
    parameterMinPacketLength: settingsService.PARAMETER_MIN_PACKET_LENGTH,
    protocolIndex,
    storageProtocolImplementationEntryMeta: '从机实现与结构体定义参考',
    storageProtocolImplementationView: protocolImplementation.VIEW_ID,
    protocolOptions,
    protocolText: protocol.label,
    toolEntries: toolNavigation.getToolEntries()
  }
}

module.exports = {
  getSettingsPageState
}
