const {
  BYTE_ORDER_HIGH,
  appendCrc16Ccitt,
  crc16Ccitt,
  hasValidCrc16Ccitt
} = require('../../utils/crc.js')

const BOOTLOADER_HEAD = [0x46, 0x54]
const ACK = 0x06
const NAK = 0x15
const PROGRAM_CHUNK_SIZE = 128
const BOOTLOADER_CRC_OPTIONS = {
  byteOrder: BYTE_ORDER_HIGH
}

function isBootloaderFrame(bytes) {
  return Array.isArray(bytes)
    && bytes.length >= 2
    && bytes[0] === BOOTLOADER_HEAD[0]
    && bytes[1] === BOOTLOADER_HEAD[1]
}

function getBootloaderResponseLength(bytes) {
  if (!isBootloaderFrame(bytes) || bytes.length < 3) return 0
  if (bytes[2] === 0x39) return 15
  if (bytes[2] === 0x19) return 9

  return 8
}

function getBootloaderExpectedLength(kind) {
  if (kind === 'handshake') return 15
  if (kind === 'flashCheck') return 9

  return 8
}

function toHex(value, length = 2) {
  return Number(value || 0).toString(16).toUpperCase().padStart(length, '0')
}

function formatBootloaderCrc(value) {
  return `0x${toHex(value, 4)}`
}

function calculateBootloaderCrc(bytes) {
  return crc16Ccitt(Array.prototype.slice.call(bytes || []), BOOTLOADER_CRC_OPTIONS)
}

function buildBootloaderFrame(payload) {
  return new Uint8Array(appendCrc16Ccitt(BOOTLOADER_HEAD.concat(payload), BOOTLOADER_CRC_OPTIONS))
}

function buildHandshakeFrame() {
  return buildBootloaderFrame([0x39, 0x42, 0x4C])
}

function buildUnlockFrame() {
  return buildBootloaderFrame([0x08, 0x4E, 0x00])
}

function buildProgramFrame(address, dataBytes, chunkSize = PROGRAM_CHUNK_SIZE) {
  const payload = [
    0x44,
    address & 0xFF,
    (address >> 8) & 0xFF
  ]
  const data = Array.prototype.slice.call(dataBytes || []).slice(0, chunkSize)

  while (data.length < chunkSize) {
    data.push(0x00)
  }

  return buildBootloaderFrame(payload.concat(data))
}

function buildFlashCheckFrame() {
  return buildBootloaderFrame([0x19, 0x43, 0x43])
}

function buildPageEraseFrame(enabled) {
  return buildBootloaderFrame([0x08, 0x50, enabled ? 0x45 : 0x44])
}

function buildExitFrame() {
  return buildBootloaderFrame([0x08, 0x42, 0x42])
}

function parseAsciiField(bytes, offset, length) {
  const chars = []

  for (let index = 0; index < length; index += 1) {
    const byte = bytes[offset + index] & 0xFF
    if (byte === 0x00 || byte === 0xFF) continue
    if (byte >= 0x20 && byte <= 0x7E) {
      chars.push(String.fromCharCode(byte))
    }
  }

  return chars.join('').trim() || '--'
}

function alignBootloaderBuffer(buffer) {
  let headIndex = -1

  for (let index = 0; index < buffer.length - 1; index += 1) {
    if (buffer[index] === BOOTLOADER_HEAD[0] && buffer[index + 1] === BOOTLOADER_HEAD[1]) {
      headIndex = index
      break
    }
  }

  if (headIndex > 0) {
    buffer.splice(0, headIndex)
  } else if (headIndex < 0 && buffer.length > 1) {
    buffer.splice(0, buffer.length - 1)
  }
}

function parseBootloaderResponse(bytes, kind) {
  if (!hasValidCrc16Ccitt(bytes, BOOTLOADER_CRC_OPTIONS)) {
    throw new Error('Bootloader 返回帧 CRC 校验失败')
  }

  if (kind === 'handshake') {
    if (bytes.length !== 15 || bytes[2] !== 0x39 || bytes[3] !== 0x42 || bytes[4] !== 0x4C) {
      throw new Error('握手反馈帧不匹配')
    }

    const versionText = parseAsciiField(bytes, 5, 4)
    const chipIdText = parseAsciiField(bytes, 9, 4)

    return {
      chipId: chipIdText,
      chipIdText,
      version: versionText,
      versionText
    }
  }

  if (kind === 'unlock') {
    if (bytes.length !== 8 || bytes[2] !== 0x08 || bytes[3] !== 0x4E || bytes[4] !== 0x00) {
      throw new Error('解锁反馈帧不匹配')
    }

    return {
      ack: bytes[5]
    }
  }

  if (kind === 'program') {
    if (bytes.length !== 8 || bytes[2] !== 0x44) {
      throw new Error('编程反馈帧不匹配')
    }

    return {
      ack: bytes[5],
      address: (bytes[3] & 0xFF) | ((bytes[4] & 0xFF) << 8)
    }
  }

  if (kind === 'flashCheck') {
    if (bytes.length !== 9 || bytes[2] !== 0x19 || bytes[3] !== 0x43 || bytes[4] !== 0x43) {
      throw new Error('全 Flash 校验反馈帧不匹配')
    }

    const flashCrc = ((bytes[5] & 0xFF) << 8) | (bytes[6] & 0xFF)

    return {
      flashCrc,
      flashCrcText: formatBootloaderCrc(flashCrc)
    }
  }

  if (kind === 'pageErase') {
    if (bytes.length !== 8 || bytes[2] !== 0x08 || bytes[3] !== 0x50) {
      throw new Error('页擦除反馈帧不匹配')
    }

    return {
      ack: bytes[5],
      enabled: bytes[4] === 0x45
    }
  }

  return {}
}

function assertBootloaderAck(response, label) {
  if (!response || response.ack === ACK) return
  if (response.ack === NAK) throw new Error(`${label}失败：设备返回 NAK`)

  throw new Error(`${label}失败：未知 ACK 0x${toHex(response.ack)}`)
}

module.exports = {
  ACK,
  BOOTLOADER_HEAD,
  BOOTLOADER_CRC_OPTIONS,
  NAK,
  PROGRAM_CHUNK_SIZE,
  alignBootloaderBuffer,
  assertBootloaderAck,
  buildBootloaderFrame,
  buildExitFrame,
  buildFlashCheckFrame,
  buildHandshakeFrame,
  buildPageEraseFrame,
  buildProgramFrame,
  buildUnlockFrame,
  calculateBootloaderCrc,
  formatBootloaderCrc,
  getBootloaderExpectedLength,
  getBootloaderResponseLength,
  isBootloaderFrame,
  parseBootloaderResponse,
  toHex
}
