package utils

import (
	"time"

	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/rs/zerolog"
)

var (
	outOfOrderSignalMap      = make(map[string]uint)
	outOfOrderVINMap         = make(map[string]uint)
	outOfOrderCount     uint = 0
	outOfOrderLogDelay       = time.Hour
	outOfOrderTime           = time.Now().UTC()
)

// This function is for aggregating and logging out of order incoming messages
func LogOutOfOrderMsg(signal string, VIN string) {
	_, ok := outOfOrderSignalMap[signal]
	if !ok {
		outOfOrderSignalMap[signal] = 0
	}
	outOfOrderSignalMap[signal] += 1

	_, ok = outOfOrderVINMap[VIN]
	if !ok {
		outOfOrderVINMap[VIN] = 0
	}
	outOfOrderVINMap[VIN] += 1
	outOfOrderCount += 1

	if time.Since(outOfOrderTime) > outOfOrderLogDelay {

		signalDict := zerolog.Dict()
		for k, v := range outOfOrderSignalMap {
			signalDict.Uint(k, v)
		}
		vinDict := zerolog.Dict()
		for k, v := range outOfOrderVINMap {
			vinDict.Uint(k, v)
		}

		logger.Warn().Dict(
			"Signals", signalDict,
		).Dict(
			"VINs", vinDict,
		).Msgf("Received Out of Order Data! %d out-of-order messages", outOfOrderCount)

		outOfOrderCount = 0
		outOfOrderTime = time.Now().UTC()
		clear(outOfOrderSignalMap)
		clear(outOfOrderVINMap)
	}
}
