package config

import (
	"fmt"
	"local/args"
	"local/logb"
	"local/storage"
	"os"
	"strings"
)

var (
	Port        string
	OAuthServer string
	Store       storage.DB
	StoreType   string
	StoreAddr   string
	StoreUser   string
	StorePass   string
	Root        string
	Config      string
)

func init() {
	Refresh()
}

func Refresh() {
	if strings.Contains(fmt.Sprint(os.Args), " -test") {
		return
	}

	as := args.NewArgSet()
	as.Append(args.STRING, "port", "port to listen on", "49809")
	as.Append(args.STRING, "oauth", "oauth URL", "")
	as.Append(args.STRING, "storetype", "storage type", "map")
	as.Append(args.STRING, "storeaddr", "storage address", "")
	as.Append(args.STRING, "storeuser", "storage username", "")
	as.Append(args.STRING, "storepass", "storage password", "")
	as.Append(args.STRING, "root", "root for static files", "./public")
	as.Append(args.STRING, "config", "cron config to load;; non-persisting", "")
	as.Append(args.STRING, "level", "log level", "info")
	if err := as.Parse(); err != nil {
		panic(err)
	}

	logb.Set(logb.LevelFromString(as.Get("level").GetString()))

	Port = ":" + strings.TrimPrefix(as.Get("port").GetString(), ":")
	OAuthServer = as.Get("oauth").GetString()
	StoreType = as.Get("storetype").GetString()
	StoreAddr = as.Get("storeaddr").GetString()
	StoreUser = as.Get("storeuser").GetString()
	StorePass = as.Get("storepass").GetString()
	Root = as.Get("root").GetString()
	Config = as.Get("config").GetString()

	if Config != "" {
		StoreType = "map"
	}

	if db, err := storage.New(storage.TypeFromString(StoreType), StoreAddr, StoreUser, StorePass); err != nil {
		panic(err)
	} else {
		Store = db
	}
}
