const modbusAccess = require('./modbus-access')
const {
  parseHexInteger
} = require('./base-utils')
const {
  controlButtonRegisters
} = require('./registers')

function getControlButton(key) {
  return controlButtonRegisters.find((item) => item.key === key) || null
}

function getControlButtonWriteValue(button) {
  if (!button) return 0

  return button.writeValue
}

async function writeControlButton(button, options = {}) {
  if (!button) return false

  const slaveAddress = modbusAccess.getSharedSlaveAddress()
  if (slaveAddress === null) return false

  const address = parseHexInteger(button.address)
  const coilEnabled = Number(getControlButtonWriteValue(button)) !== 0

  return modbusAccess.writeSingleCoil(
    slaveAddress,
    address,
    coilEnabled,
    options.label || button.name,
    options.kind || 'motor-control-write',
    {
      showModal: options.showModal
    }
  )
}

function writeControlButtonByKey(key, options = {}) {
  return writeControlButton(getControlButton(key), options)
}

function softReset(options = {}) {
  return writeControlButtonByKey('reset', {
    label: '软复位',
    kind: 'motor-control-soft-reset',
    showModal: false,
    ...options
  })
}

module.exports = {
  getControlButton,
  softReset,
  writeControlButton,
  writeControlButtonByKey
}
