const {
  statusRegisters
} = require('./registers')
const {
  MAX_USER_STATUS_COUNT,
  getUserStatusCount
} = require('./control-page-state')
const {
  formatStatusRegisters
} = require('./status-format')

const STATUS_SUMMARY_METRICS = [
  { key: 'speed', name: '估算速度', unit: 'RPM', decimals: 0 },
  { key: 'voltage', name: '母线电压', unit: 'V', decimals: 1 },
  { key: 'power', name: '估算功率', unit: 'W', decimals: 1 },
  { key: 'temperature', name: 'NTC 温度', unit: '℃', decimals: 0 }
]

function getVisibleStatusRegisters(userStatusCount) {
  const count = getUserStatusCount(userStatusCount)

  return statusRegisters.filter((item) => (
    item.name.indexOf('用户状态字') !== 0 ||
    Number(item.name.replace('用户状态字 ', '')) <= count
  ))
}

function getStatusPageState(userStatusCount) {
  return {
    maxUserStatusCount: MAX_USER_STATUS_COUNT,
    statusRegisters: formatStatusRegisters(getVisibleStatusRegisters(userStatusCount))
  }
}

function getFormattedStatusMap() {
  const formattedRegisters = formatStatusRegisters(statusRegisters)

  return formattedRegisters.reduce((result, item) => {
    result[item.name] = item
    return result
  }, {})
}

function formatMetricText(item, unit, decimals) {
  if (!item || item.displayValue === undefined || item.displayValue === '--') return '--'

  const numberValue = Number(item.displayValue)
  const displayValue = Number.isFinite(numberValue)
    ? numberValue.toFixed(decimals)
    : String(item.displayValue)

  return `${displayValue}${unit}`
}

function getStatusSummaryState() {
  const registerMap = getFormattedStatusMap()
  const stateValue = registerMap['状态机'] && registerMap['状态机'].displayValue
  const faultValue = registerMap['故障码'] && registerMap['故障码'].displayValue
  const faultText = faultValue || '--'
  const isFault = faultText !== '--' && faultText !== '无故障'

  return {
    faultClass: isFault ? 'is-warning' : '',
    faultText,
    metrics: STATUS_SUMMARY_METRICS.map((config) => ({
      key: config.key,
      displayText: formatMetricText(registerMap[config.name], config.unit, config.decimals)
    })),
    stateText: stateValue || '--'
  }
}

module.exports = {
  getStatusPageState,
  getStatusSummaryState
}
