package config

import (
	"strings"

	flag "github.com/spf13/pflag"
	"github.com/spf13/viper"
)

type dbConfig struct {
	Type             string
	ConnectionString string
}
type webConfig struct {
	Host string
	Port int
}
type radarConfig struct {
	Baud int
	Port string
}
type config struct {
	BaseUrl string

	DB  dbConfig
	Web webConfig

	PrinterPort string

	Radar       radarConfig
	SpeedsignIP string
}

var C config

func init() {
	flag.String("host", "127.0.0.1", "Weberser Bind IP")
	flag.Int("port", 3000, "Webserver Port")
	flag.String("db-type", "sqlite", "Database Type")
	flag.String("db", "db.sqlite", "Database String")
	flag.String("base-url", "http://localhost:3001", "Base URL of the frontend")
	flag.String("printer-port", "", "Serial port for printer")
	flag.String("radar-port", "", "Radar port")
	flag.Int("radar-baud", 9600, "Radar Baudrate")
	flag.Int("mail-smtp-port", 587, "Mail Port")
	flag.String("speedsign-ip", "", "192.168.1.143")
	_ = viper.BindPFlags(flag.CommandLine)

	flag.Parse()

	viper.SetConfigName("config")
	viper.AddConfigPath(".")
	viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
	viper.AutomaticEnv()

	C = config{
		BaseUrl:     viper.GetString("base-url"),
		PrinterPort: viper.GetString("printer-port"),
		SpeedsignIP: viper.GetString("speedsign-ip"),
		DB: dbConfig{
			Type:             viper.GetString("db-type"),
			ConnectionString: viper.GetString("db"),
		},
		Web: webConfig{
			Host: viper.GetString("host"),
			Port: viper.GetInt("port"),
		},
		Radar: radarConfig{
			Baud: viper.GetInt("radar-baud"),
			Port: viper.GetString("radar-port"),
		},
	}
}
