import type {
  MachineDailyUsageStat,
  MachineStateCode,
  MachineTelemetryInterval,
} from '../model/types'
import { mockMachineTelemetryIntervals } from './mockMachineTelemetryIntervals'

type DailyTotals = Omit<MachineDailyUsageStat, 'utilizationPercent'>

const emptyStateTotals: Record<MachineStateCode, keyof Pick<
  DailyTotals,
  'movingSeconds' | 'engineOnSeconds' | 'idleSeconds' | 'noDataSeconds'
>> = {
  MOVING: 'movingSeconds',
  ENGINE_ON: 'engineOnSeconds',
  IDLE: 'idleSeconds',
  NO_DATA: 'noDataSeconds',
}

function getIntervalDate(interval: MachineTelemetryInterval) {
  return interval.startedAt.slice(0, 10)
}

function getUtilizationPercent(total: DailyTotals) {
  const knownSeconds = total.movingSeconds + total.engineOnSeconds + total.idleSeconds

  if (knownSeconds <= 0) return 0

  return Math.round((total.movingSeconds / knownSeconds) * 100)
}

function buildDailyUsageStats() {
  const statsByMachineAndDate = new Map<string, DailyTotals>()

  mockMachineTelemetryIntervals.forEach((interval) => {
    const date = getIntervalDate(interval)
    const key = `${interval.machineId}-${date}`
    const current = statsByMachineAndDate.get(key) ?? {
      machineId: interval.machineId,
      date,
      movingSeconds: 0,
      engineOnSeconds: 0,
      idleSeconds: 0,
      noDataSeconds: 0,
    }

    current[emptyStateTotals[interval.state]] += interval.durationSeconds
    statsByMachineAndDate.set(key, current)
  })

  return Array.from(statsByMachineAndDate.values())
    .map((total) => ({
      ...total,
      utilizationPercent: getUtilizationPercent(total),
    }))
    .sort((first, second) => {
      if (first.machineId !== second.machineId) {
        return first.machineId - second.machineId
      }

      return first.date.localeCompare(second.date)
    })
}

export const mockMachineDailyUsageStats: MachineDailyUsageStat[] = buildDailyUsageStats()
