package signature

import (
	"sync"

	"code.justin.tv/sse/malachai/pkg/registration"
)

type serviceCache struct {
	sync.RWMutex
	registrar ServiceRegistrar
	cache     map[string]*registration.Service
}

// GetServiceByID retrieves the service from an in memory map. If it doesn't
// exist in cache, query the registration dynamodb table and fill cache.
func (sc *serviceCache) GetServiceByID(id string) (svc *registration.Service, err error) {
	var ok bool
	sc.RLock()
	svc, ok = sc.cache[id]
	sc.RUnlock()
	if ok {
		return
	}

	svc, err = sc.registrar.GetServiceByID(id)
	if err != nil {
		return
	}

	sc.Lock()
	sc.cache[svc.ID] = svc
	sc.Unlock()

	return
}
