package digitaltwin

import (
	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/logger"
)

// var existsCount ExistsCount

type DigitalTwinCacheInterface interface {
	Exists(vin string, prop string, value interface{}) bool
}

type DigitalTwinCache struct {
	ringMap    *cache.RingMap
	// existsChan chan<- bool
}

func NewDigitalTwinCache(capacity int) DigitalTwinCacheInterface {
	// existsChannel := make(chan bool, 100)
	// existsCount = ExistsCount{
	// 	Channel: existsChannel,
	// }
	// go existsCount.Run()
	return &DigitalTwinCache{
		ringMap:    cache.NewRingMap(capacity),
		// existsChan: existsChannel,
	}
}

func (d *DigitalTwinCache) Exists(vin string, prop string, value interface{}) bool {
	exists := d.ringMap.Exists(vin+prop, value)
	// If the channel is full, we just fall through
	// select {
	// case d.existsChan <- exists:
	// default:
	// }
	return exists
}

type ExistsCount struct {
	Total   int
	Exists  int
	Channel <-chan bool
}

func (ec *ExistsCount) Run() {
	for exists := range ec.Channel {
		ec.Total++
		if exists {
			ec.Exists += 1
		}
		if ec.Total >= 180000000 {
			logger.Error().Int("Cached Entries", ec.Exists).Int("Total Entries", ec.Total).Msg("Digital Twin Cache Results")
			ec.Total = 0
			ec.Exists = 0
		}
	}
}
