package locator

import (
	perr "git.markbailey.dev/cervers/ptpp/lib/error"
	"git.markbailey.dev/cervers/ptpp/lib/locator/service"
	"sync"
)

type Locator struct {
	services map[string]service.Service
	mu       sync.RWMutex
}

func (l *Locator) Register(s service.Service) {
	l.mu.Lock()
	defer l.mu.Unlock()

	if l.services == nil {
		l.services = make(map[string]service.Service)
	}
	l.services[s.Name()] = s
}

func (l *Locator) Locate(name string) (service.Service, error) {
	l.mu.RLock()
	defer l.mu.RUnlock()

	s, ok := l.services[name]
	if !ok {
		return nil, perr.Wrap(service.ErrServiceNotFound{Name: name}, "locator")
	}
	return s, nil
}
