const storageAccessService = require('../storage-access/service.js')
const transport = require('../../transport/ble-core.js')
const {
  bytesToHex,
  stringToUtf8Bytes
} = require('../../utils/binary-utils.js')
const {
  parseHexBytes,
  validateHexText
} = require('../../utils/validation.js')
const {
  normalizeSerialState
} = require('./view-model.js')

async function sendSerialFrame(data = {}) {
  const serialInputText = String(data.serialInputText || '')
  const serialState = normalizeSerialState(data)
  const mode = serialState.serialMode

  if (!data.connectedDevice) {
    return {
      errorText: '请先连接蓝牙设备',
      ok: false
    }
  }

  if (serialState.serialErrorText) {
    return {
      errorText: serialState.serialErrorText,
      ok: false
    }
  }

  if (mode === 'hex') {
    const errorText = validateHexText(serialInputText)
    if (errorText) {
      return {
        errorText,
        ok: false
      }
    }

    const bytes = parseHexBytes(serialInputText)
    const previewHex = bytesToHex(bytes, ' ')
    const ok = await transport.sendRawFrameExact(new Uint8Array(bytes), 'SERIAL')

    return {
      bytes,
      ok,
      previewHex,
      serialState
    }
  }

  const bytes = stringToUtf8Bytes(serialInputText)
  if (!bytes.length) {
    return {
      errorText: '请输入要发送的文本',
      ok: false
    }
  }

  const ok = await transport.sendRawFrameExact(new Uint8Array(bytes), 'SERIAL')

  return {
    bytes,
    ok,
    previewHex: bytesToHex(bytes, ' '),
    serialState
  }
}

async function executeStorageAccessProtocol(data = {}) {
  if (!data.connectedDevice) {
    return {
      errorText: '请先连接蓝牙设备',
      ok: false
    }
  }

  try {
    return await storageAccessService.executeMemoryCommand(data, {
      maxPacketLength: data.parameterMaxPacketLength,
      showModal: true
    })
  } catch (error) {
    return {
      errorText: error.message || '存储访问命令无效',
      ok: false
    }
  }
}

async function executeStorageAccessSpecialCommand(command = {}, data = {}) {
  if (!data.connectedDevice) {
    return {
      errorText: '请先连接蓝牙设备',
      ok: false
    }
  }

  if (!command || !command.op) {
    return {
      errorText: '特殊指令无效',
      ok: false
    }
  }

  return storageAccessService.executeControlCommand(command.key, data, {
    maxPacketLength: data.parameterMaxPacketLength,
    showModal: true
  })
}

module.exports = {
  executeStorageAccessProtocol,
  executeStorageAccessSpecialCommand,
  sendSerialFrame
}
