const PROTOCOL_MODE = {
  MODBUS_RTU: 'modbus-rtu',
  NONE: 'none',
  STORAGE_ACCESS: 'storage-access'
}

const PROTOCOL_OPTIONS = [
  { key: PROTOCOL_MODE.NONE, label: '无协议' },
  { key: PROTOCOL_MODE.STORAGE_ACCESS, label: '存储访问' },
  { key: PROTOCOL_MODE.MODBUS_RTU, label: '标准Modbus' }
]

const DEFAULT_PROTOCOL_MODE = PROTOCOL_MODE.STORAGE_ACCESS

function normalizeProtocolMode(value, fallback = DEFAULT_PROTOCOL_MODE) {
  const key = String(value || '').trim()
  const matched = PROTOCOL_OPTIONS.find((option) => option.key === key)

  if (matched) return matched.key

  return fallback
}

function isModbusProtocolMode(value) {
  return normalizeProtocolMode(value) === PROTOCOL_MODE.MODBUS_RTU
}

function isStorageAccessProtocolMode(value) {
  return normalizeProtocolMode(value) === PROTOCOL_MODE.STORAGE_ACCESS
}

function isNoProtocolMode(value) {
  return normalizeProtocolMode(value) === PROTOCOL_MODE.NONE
}

module.exports = {
  DEFAULT_PROTOCOL_MODE,
  PROTOCOL_MODE,
  PROTOCOL_OPTIONS,
  isModbusProtocolMode,
  isNoProtocolMode,
  isStorageAccessProtocolMode,
  normalizeProtocolMode
}
