package models

import (
	"fmt"
	"sync"

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
)

var (
	max_invalid_cache    = envtool.GetEnvInt("MAX_INVALID_CANID_CACHE", 100)
	invalidCANIDOnce     sync.Once
	invalidCANIDInstance InvalidCANIDCacheInterface
)

func NewInvalidCANIDCache() InvalidCANIDCacheInterface {
	return &InvalidCANIDCache{
		ringMap: cache.NewRingMap(max_invalid_cache),
	}
}

func GetInvalidCANIDCache() InvalidCANIDCacheInterface {
	invalidCANIDOnce.Do(func() {
		if invalidCANIDInstance == nil {
			invalidCANIDInstance = NewInvalidCANIDCache()
		}
	})

	return invalidCANIDInstance
}

func SetInvalidCANIDCache(instance InvalidCANIDCacheInterface) {
	invalidCANIDInstance = instance
}

type InvalidCANIDCacheInterface interface {
	Exists(dbc string, can_id int32) bool
}

type InvalidCANIDCache struct {
	ringMap *cache.RingMap
}

func (i *InvalidCANIDCache) Exists(dbc string, can_id int32) bool {
	return !i.ringMap.Set(fmt.Sprintf("%s:%d", dbc[0:4], can_id), false)
}
