package config

import (
	"context"
	"local/args"
	"local/storage"
	"os"
)

func New() error {
	as := args.NewArgSet()
	as.Append(args.STRING, "addr", "address/path to database/file", "")
	as.Append(args.STRING, "user", "username to database", "")
	as.Append(args.STRING, "pass", "password to database", "")
	as.Append(args.STRING, "port", "port to listen on", "33419")
	as.Append(args.STRING, "db", "database type code", storage.MAP.String())
	as.Append(args.STRING, "ns", "namespace", storage.DefaultNamespace)
	as.Append(args.STRING, "proxy", "http proxy", "")
	if err := as.Parse(); err != nil {
		return err
	}
	if proxy := as.Get("proxy").GetString(); len(proxy) > 0 {
		os.Setenv("http_proxy", proxy)
	}
	ctx, can := context.WithCancel(context.Background())
	config = Config{
		db:               as.Get("db").GetString(),
		Addr:             as.Get("addr").GetString(),
		Username:         as.Get("user").GetString(),
		Password:         as.Get("pass").GetString(),
		Port:             as.Get("port").GetString(),
		DefaultNamespace: as.Get("ns").GetString(),
		Ctx:              ctx,
		Can:              can,
	}
	storage.DefaultNamespace = config.DefaultNamespace
	DB, err := storage.New(storage.TypeFromString(config.db), config.Addr, config.Username, config.Password)
	config.DB = DB
	return err
}

func orEnv(def, key string, keys ...string) string {
	for _, key := range append(keys, key) {
		if v, ok := os.LookupEnv(key); ok {
			return v
		}
	}
	return def
}
