package registry

import (
	"fmt"
	"github.com/spf13/viper"
	"sync"
)

var (
	mu      sync.RWMutex
	configs = make(map[string]Config)
)

// RegisterConfig registers a Config with given name.
func RegisterConfig(name string, config Config) {
	mu.Lock()
	defer mu.Unlock()

	_, ok := configs[name]
	if ok {
		panic(fmt.Sprintf("a config with name %s already exist", name))
	}

	configs[name] = config
}

// GetConfig returns a Config with given name.
func GetConfig(name string) Config {
	mu.RLock()
	defer mu.RUnlock()

	config, ok := configs[name]
	if !ok {
		return nil
	}

	return config
}

// SetDefaultConfigs attempts to run all set-default functions of all registered configs.
func SetDefaultConfigs(v *viper.Viper) {
	mu.RLock()
	defer mu.RUnlock()

	for _, config := range configs {
		config.SetDefault(v)
	}
}
