const {
  MODBUS_CRC_OPTIONS,
  hasValidCrc16Modbus
} = require('./modbus-rtu/frame.js')
const {
  getReadBufferHint,
  parseModbusRequest,
  readResponseFromBuffer
} = require('./modbus-rtu/response.js')
const {
  getBootloaderResponseLength,
  isBootloaderFrame
} = require('./bootloader/frame.js')
const {
  BYTE_ORDER_HIGH,
  hasValidCrc16Ccitt
} = require('../utils/crc.js')

function inspectReceivedBytes(rawBytes, context = {}) {
  if (!Array.isArray(rawBytes) || rawBytes.length < 4) return ''

  if (isBootloaderFrame(rawBytes)) {
    const expectedLength = getBootloaderResponseLength(rawBytes)
    if (expectedLength && rawBytes.length < expectedLength) return '片段'

    return hasValidCrc16Ccitt(rawBytes, { byteOrder: BYTE_ORDER_HIGH }) ? 'CRC OK' : 'CRC ERR'
  }

  return hasValidCrc16Modbus(rawBytes, MODBUS_CRC_OPTIONS) ? 'CRC OK' : (context.pendingRequest ? '片段' : 'CRC ERR')
}

function parseSendExpected(bytes) {
  return parseModbusRequest(bytes)
}

module.exports = {
  getResponseBufferHint: getReadBufferHint,
  inspectReceivedBytes,
  parseSendExpected,
  readResponseFromBuffer
}
