package SunnyProxy

import (
	"Sunny/src/crypto/tls"
	"sync"
)

type Cache struct {
	M           sync.Map
	singleGroup *Group
}

func NewCache() *Cache {
	return &Cache{
		singleGroup: &Group{},
	}
}

func (cache *Cache) GetOrStore(key string, fn func() (interface{}, error)) (interface{}, error) {
	if val, ok := cache.M.Load(key); ok {
		return val.(tls.Certificate), nil
	}

	cert, err := cache.singleGroup.Do(key, fn)
	if err != nil {
		return nil, err
	}
	cache.M.Store(key, cert)
	return cert.(tls.Certificate), nil
}

func (cache *Cache) GetCache() sync.Map {
	return cache.M
}
