const storageAccessProtocol = require('../../protocols/storage-access/index.js')
const settingsService = require('../../store/settings-store.js')

function resolveMaxPacketLength(value) {
  const settings = settingsService.getState()
  const numberValue = Number(value === undefined ? settings.parameterMaxPacketLength : value)
  if (Number.isFinite(numberValue) && Math.round(numberValue) === 0) return 0
  if (Number.isFinite(numberValue) && numberValue > 0) return Math.round(numberValue)

  return 64
}

function normalizeTransferOptions(options = {}) {
  const maxPacketLength = options.maxPacketLength === undefined ? options.maxFrameBytes : options.maxPacketLength

  return {
    maxFrameBytes: resolveMaxPacketLength(maxPacketLength),
    onChunk: options.onChunk,
    showModal: options.showModal !== false
  }
}

async function readMemory(area, startAddress, byteLength, label, kind, options = {}) {
  return storageAccessProtocol.client.readMemory(
    area,
    startAddress,
    byteLength,
    label,
    kind,
    normalizeTransferOptions(options)
  )
}

async function writeMemory(area, startAddress, bytes, label, kind, options = {}) {
  return storageAccessProtocol.client.writeMemory(
    area,
    startAddress,
    bytes,
    label,
    kind,
    normalizeTransferOptions(options)
  )
}

async function readCodeInfoBlock(label, kind, options = {}) {
  return storageAccessProtocol.client.readCodeInfoBlock(
    label,
    kind,
    normalizeTransferOptions(options)
  )
}

module.exports = {
  AREA: storageAccessProtocol.AREA,
  readCodeInfoBlock,
  readMemory,
  resolveMaxPacketLength,
  writeMemory
}
