package config

import (
	"errors"

	"github.com/BurntSushi/toml"
	log "github.com/sirupsen/logrus"
)

type Config struct {
	Database database
	Server   server
	Settings settings
	Crontab  crontab
}

type database struct {
	Engine    string
	DBFile    string
	Tablename string
}

type server struct {
	Port       string
	AppLogPath string
}

type settings struct {
	InitDate string
}

type crontab struct {
	Exchangerateonday string
}

var GlobalDate string = "01.01.1970"

// InitConf - read config data
func InitConf(p string) Config {
	var conf Config

	if _, err := toml.DecodeFile(p, &conf); err != nil {
		log.Errorf("Configuration decode error: %s", err)
	}
	SetGlobalDate(conf.Settings.InitDate)
	return conf
}

// ValidateDBEngine - Validate engine value in config
func ValidateDBEngine(c string) error {
	switch c {
	case "sqlite":
		return nil
	}
	log.Errorf("Unsupported database engine: %s", c)
	return errors.New("unsupported database engine")
}

func SetGlobalDate(s string) {
	GlobalDate = s
	log.Printf("Globaldate set to %s", s)
}

func GetGlobalDate() string {
	return GlobalDate
}
