package config

import (
	"log"

	"github.com/knadh/koanf"
	"github.com/knadh/koanf/parsers/toml"
	"github.com/knadh/koanf/providers/confmap"
	kfile "github.com/knadh/koanf/providers/file"
)

func LoadConfig(errFatalOnMissing bool) (*koanf.Koanf, *kfile.File) {
	// Main config variable
	var pfConfig = koanf.New(".")

	// Setup defaults
	pfConfig.Load(confmap.Provider(map[string]interface{}{
		CONFIG_KEY_SLIDESHOW_INTERVAL:         DEFAULT_SLIDESHOW_INTERVAL,
		CONFIG_KEY_SLIDESHOW_RESTART_INTERVAL: DEFAULT_SLIDESHOW_RESTART_INTERVAL,
		CONFIG_KEY_HDMI_OFF:                   DEFAULT_HDMI_OFF,
		CONFIG_KEY_HDMI_ON:                    DEFAULT_HDMI_ON,
		CONFIG_KEY_ALBUMS_ROOT:                DEFAULT_ALBUMS_ROOT,
		CONFIG_KEY_ALBUMS_SELECTED:            DEFAULT_ALBUM_SELECTED,
		CONFIG_KEY_FAN_POLL_INTERVAL:          DEFAULT_FAN_POLL_INTERVAL,
		CONFIG_KEY_FAN_SPEEDS:                 DEFAULT_FAN_SPEEDS,
		CONFIG_KEY_FAN_MIN_SPEED:              DEFAULT_FAN_MIN_SPEED,
	}, "."), nil)

	// Bring in /etc/defaults/pf.toml if it exists
	configFileProvider := kfile.Provider(CONFIG_FILE_PATH)
	if err := pfConfig.Load(configFileProvider, toml.Parser()); err != nil {
		if errFatalOnMissing {
			log.Fatalf("Error loading config : %s", err)
		} else {
			log.Printf("Error loading config : %s", err)
		}
	}

	return pfConfig, configFileProvider
}
