import { ref } from 'vue'
import { formatChartTime } from '@/utils/datetime'

const MAX_POINTS = 36

export function useMetricHistory() {
  const labels = ref([])
  const cpu = ref([])
  const memory = ref([])
  const inlet = ref([])
  const exportFlow = ref([])

  function trim(arr) {
    return arr.length > MAX_POINTS ? arr.slice(-MAX_POINTS) : arr
  }

  function record(snapshot) {
    labels.value = trim([...labels.value, formatChartTime()])
    cpu.value = trim([...cpu.value, Number(snapshot.cpu_percent?.toFixed?.(1) ?? 0)])
    memory.value = trim([...memory.value, Number(snapshot.mem_percent?.toFixed?.(1) ?? 0)])
    inlet.value = trim([...inlet.value, snapshot.inlet_flow ?? 0])
    exportFlow.value = trim([...exportFlow.value, snapshot.export_flow ?? 0])
  }

  return { labels, cpu, memory, inlet, exportFlow, record }
}
