package config

import (
	"fmt"
	"os"
	"strings"

	"github.com/joho/godotenv"
)

var Cfg Config

type Config struct {
	Debug                       bool
	ColorizedOutput             bool
	Host                        string
	Port                        string
	LogManagerServerUrl         string
	TelegramBotManagerEnabled   bool
	TelegramBotManagerServerUrl string
	FolderPaths                 FolderPaths
	MariaDB                     MariaDB
	InvexAPI                    InvexAPI
	NotificationUserIds         []string
}

type FolderPaths struct {
	GroupTasksGroups       string
	GroupTasksRunningTasks string
	PublicStatic           string
}

type MariaDB struct {
	Hostname     string
	Port         string
	Username     string
	Password     string
	DatabaseName string
}

type InvexAPI struct {
	Base  string
	Token string
}

func LoadConfig() {
	// used to determine server was startet in docker or not
	if os.Getenv("DOCKER") == "" {
		fmt.Println("Load env from file")
		godotenv.Load(".env")
	} else {
		fmt.Println("Load env from system")
	}

	config := Config{
		Debug:                       os.Getenv("DEBUG") == "true",
		ColorizedOutput:             os.Getenv("COLORIZED_OUTPUT") == "true",
		LogManagerServerUrl:         os.Getenv("LOG_MANAGER_SERVER_URL"),
		TelegramBotManagerEnabled:   os.Getenv("TELEGRAM_BOT_MANAGER_ENABLED") == "true",
		TelegramBotManagerServerUrl: os.Getenv("TELEGRAM_BOT_MANAGER_SERVER_URL"),
		FolderPaths: FolderPaths{
			GroupTasksGroups:       os.Getenv("FOLDER_GROUPTASKS_GROUPS"),
			GroupTasksRunningTasks: os.Getenv("FOLDER_GROUPTASKS_RUNNINGTASKS"),
			PublicStatic:           os.Getenv("FOLDER_PUBLIC_STATIC"),
		},
		MariaDB: MariaDB{
			Hostname:     os.Getenv("MARIADB_HOSTNAME"),
			Port:         os.Getenv("MARIADB_PORT"),
			Username:     os.Getenv("MARIADB_USERNAME"),
			Password:     os.Getenv("MARIADB_PASSWORD"),
			DatabaseName: os.Getenv("MARIADB_DATABASE_NAME"),
		},
		InvexAPI: InvexAPI{
			Base:  os.Getenv("INVEX_API_BASE"),
			Token: os.Getenv("INVEX_API_TOKEN"),
		},
		NotificationUserIds: strings.Split(os.Getenv("NOTIFICATION_USER_IDS"), ","),
	}

	// load default values if not in docker
	if os.Getenv("DOCKER") == "" {
		config.Host = os.Getenv("HOST")
		config.Port = os.Getenv("PORT")
	} else { // load from docker env
		config.Host = "0.0.0.0"
		config.Port = "80"
	}

	Cfg = config
}
