package manager

import (
	"fmt"

	"dnsupdater/provider"
	"dnsupdater/provider/digitalocean"
)

var factories = map[string]provider.ProviderFactory{
	"digitalocean": digitalocean.Factory,
}

type Manager struct {
	services map[string]provider.Provider
}

func New() *Manager {
	return &Manager{
		services: make(map[string]provider.Provider),
	}
}

func (m Manager) Get(name string) provider.Provider {
	if service, ok := m.services[name]; ok {
		return service
	}
	return nil
}

func (m Manager) RegisterFromConfig(providers map[string]map[string]interface{}) error {
	for name, args := range providers {
		if factory, ok := factories[name]; ok {

			provider, err := factory(args)
			if err != nil {
				return fmt.Errorf("could not create provider '%s': %v", name, err)
			}

			m.Register(name, provider)
		}
	}
	return nil
}

func (m Manager) Register(name string, provider provider.Provider) {
	m.services[name] = provider
}
