package webrtc

import (
	"fmt"
	"sync"
)

// SourceHandle is the minimal interface the Registry stores per stream_id.
// The concrete type is *Source, defined in source.go.
type SourceHandle interface {
	ID() string
}

// Registry is a thread-safe map from stream_id to active SourceHandle.
type Registry struct {
	mu      sync.RWMutex
	streams map[string]SourceHandle
}

// NewRegistry returns an empty Registry.
func NewRegistry() *Registry {
	return &Registry{streams: make(map[string]SourceHandle)}
}

// Register associates src with streamID. Returns an error if streamID is
// already registered.
func (r *Registry) Register(streamID string, src SourceHandle) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, exists := r.streams[streamID]; exists {
		return fmt.Errorf("webrtc: stream %q already registered", streamID)
	}
	r.streams[streamID] = src
	return nil
}

// Lookup returns the handle for streamID. The second return value is false
// if no source is registered.
func (r *Registry) Lookup(streamID string) (SourceHandle, bool) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	src, ok := r.streams[streamID]
	return src, ok
}

// Deregister removes streamID. No-op if not present.
func (r *Registry) Deregister(streamID string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.streams, streamID)
}
