const {
  formatTime
} = require('./ble-utils.js')

const DEFAULT_MAX_LOG_COUNT = 100

function createLogItem(direction, payload, note = '', extras = {}, sequence = 0, timestamp = Date.now()) {
  return {
    id: `log-${timestamp}-${sequence}`,
    direction,
    note,
    payloadBytes: Array.isArray(extras.payloadBytes) ? extras.payloadBytes.slice() : null,
    payloadText: typeof extras.payloadText === 'string' ? extras.payloadText : '',
    payload,
    time: formatTime(timestamp)
  }
}

function appendLog(logs = [], logItem, maxLogCount = DEFAULT_MAX_LOG_COUNT) {
  const limit = Math.max(1, Number(maxLogCount) || DEFAULT_MAX_LOG_COUNT)

  return logs.concat(logItem).slice(-limit)
}

function createClearLogsState() {
  return {
    logScrollTarget: '',
    logs: [],
    rxCount: 0,
    txCount: 0
  }
}

module.exports = {
  DEFAULT_MAX_LOG_COUNT,
  appendLog,
  createClearLogsState,
  createLogItem
}
