const settingsService = require('./settings-service')
const themeService = require('./theme-service')
const controlState = require('./control-page-state')
const toolNavigation = require('./tool-navigation')

function getModbusProtocolMeta(settingsState) {
  const modbusProtocolOptions = settingsService.MODBUS_PROTOCOL_OPTIONS
  const modbusProtocolIndex = Math.max(0, modbusProtocolOptions.findIndex((option) => (
    option.key === settingsState.modbusProtocolFilter
  )))
  const modbusProtocolText = (modbusProtocolOptions[modbusProtocolIndex] || modbusProtocolOptions[0]).label

  return {
    isGenericProtocol: settingsState.modbusProtocolFilter === 'generic',
    modbusProtocolIndex,
    modbusProtocolOptions,
    modbusProtocolText
  }
}

function getSettingsPageState(
  settingsState = settingsService.getState(),
  themeState = themeService.getState()
) {
  const nightModeEnabledSwitch = settingsState.nightModeFollowSystem
    ? themeState.themeMode === 'dark'
    : settingsState.nightModeEnabled

  return {
    ...settingsState,
    ...themeState,
    ...getModbusProtocolMeta(settingsState),
    genericModbusMinPacketLength: settingsService.GENERIC_MODBUS_MIN_PACKET_LENGTH,
    maxUserStatusCount: controlState.MAX_USER_STATUS_COUNT,
    nightModeEnabledSwitch,
    statusPollMaxInterval: settingsService.STATUS_POLL_MAX_INTERVAL,
    statusPollMinInterval: settingsService.STATUS_POLL_MIN_INTERVAL,
    toolEntries: toolNavigation.getToolEntries()
  }
}

module.exports = {
  getModbusProtocolMeta,
  getSettingsPageState
}
