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

const READ_ONLY_MEMORY_AREAS = [
  storageAccessProtocol.AREA.CODEINFO,
  storageAccessProtocol.AREA.CODE
]

const MANUAL_MEMORY_AREAS = [
  { key: storageAccessProtocol.AREA.ADDR32, label: 'addr32', name: 'ADDR32', addressWidth: 32 },
  { key: storageAccessProtocol.AREA.DATA, label: 'data', name: 'DATA' },
  { key: storageAccessProtocol.AREA.IDATA, label: 'idata', name: 'IDATA' },
  { key: storageAccessProtocol.AREA.XDATA, label: 'xdata', name: 'XDATA' },
  { key: storageAccessProtocol.AREA.CODE, label: 'code', name: 'CODE', readOnly: true }
]

function getManualMemoryAreaOptions() {
  return MANUAL_MEMORY_AREAS.map((area) => ({ ...area }))
}

function getMemoryTypeFromName(value) {
  const memoryArea = String(value || '').trim().toUpperCase()
  if (memoryArea === 'ADDR32' || memoryArea === 'ADDRESS32') return storageAccessProtocol.AREA.ADDR32
  if (memoryArea === 'BIT') return storageAccessProtocol.AREA.DATA

  const area = storageAccessProtocol.AREA[memoryArea]

  return area === undefined ? null : area
}

function isReadOnlyMemoryType(memoryType) {
  return READ_ONLY_MEMORY_AREAS.indexOf(Number(memoryType)) >= 0
}

module.exports = {
  getManualMemoryAreaOptions,
  getMemoryTypeFromName,
  isReadOnlyMemoryType,
  READ_ONLY_MEMORY_AREAS
}
