const {
  createGroupsFromCodeInfo,
  parseCodeInfo
} = require('../../domain/storage-access/code-info-parser.js')
const {
  cloneImportedGroup,
  normalizeGroup
} = require('../../domain/parameter-groups/model.js')
const memoryService = require('./memory-service.js')

function formatWordHex(value) {
  return Number(value || 0).toString(16).toUpperCase().padStart(4, '0')
}

async function syncCodeInfo(options = {}) {
  const result = await memoryService.readCodeInfoBlock(
    options.label || '同步info',
    options.kind || 'storage-info-read',
    {
      maxPacketLength: options.maxPacketLength,
      showModal: options.showModal !== false
    }
  )
  if (!result) {
    return {
      ok: false
    }
  }

  const codeInfo = parseCodeInfo(result.codeInfoBytes)
  const importedGroups = createGroupsFromCodeInfo(codeInfo, options)
    .map(cloneImportedGroup)
    .map(normalizeGroup)

  return {
    codeInfoAddress: result.codeInfoAddress,
    codeInfoAddressText: formatWordHex(result.codeInfoAddress),
    codeInfoByteLength: result.codeInfoByteLength,
    codeInfoByteLengthText: formatWordHex(result.codeInfoByteLength),
    codeInfoBytes: result.codeInfoBytes,
    codeInfo,
    infoBytes: result.infoBytes,
    groupCount: importedGroups.length,
    importedGroups,
    codeInfoMemoryType: result.codeInfoMemoryType,
    ok: true,
    structCount: codeInfo.structCount
  }
}

module.exports = {
  AREA: memoryService.AREA,
  readMemory: memoryService.readMemory,
  syncCodeInfo,
  writeMemory: memoryService.writeMemory
}
