import { computed } from 'vue'
import { formatTime, getColorForCode } from './chartFormat'

export function useChartData(observations, code) {
  const source = computed(() =>
    (typeof observations === 'function' ? observations() : observations) ?? [])

  const chartData = computed(() => {
    const filtered = source.value
      .filter(o => o.observationCode === code)
      .sort((a, b) => new Date(a.recordedAt) - new Date(b.recordedAt))

    return {
      labels: filtered.map(o => formatTime(o.recordedAt)),
      timestamps: filtered.map(o => o.recordedAt),
      datasets: [{
        label: code,
        data: filtered.map(o => o.value),
        borderColor: getColorForCode(code),
        tension: 0.3,
        pointRadius: 4,
      }],
    }
  })

  return { chartData }
}
