package config

import (
	"io/ioutil"
	"local/args"
	"os"
	"time"
)

type Config struct {
	Port         int
	DBURI        string
	Database     string
	DriverType   string
	FilePrefix   string
	FileRoot     string
	Auth         bool
	AuthLifetime time.Duration
	MaxFileSize  int64
}

func New() Config {
	as := args.NewArgSet()

	f, err := ioutil.TempFile(os.TempDir(), "bolt.db.*")
	if err != nil {
		panic(err)
	}
	f.Close()

	as.Append(args.INT, "p", "port to listen on", 18114)
	as.Append(args.STRING, "dburi", "database uri", f.Name())
	as.Append(args.STRING, "fileprefix", "path prefix for file service", "/__files__")
	as.Append(args.STRING, "fileroot", "path to file hosting root", "/tmp/")
	as.Append(args.STRING, "database", "database name to use", "db")
	as.Append(args.STRING, "drivertype", "database driver to use", "boltdb")
	as.Append(args.BOOL, "auth", "check for authorized access", false)
	as.Append(args.DURATION, "authlifetime", "duration auth is valid for", time.Hour)
	as.Append(args.INT, "max-file-size", "max file size for uploads in bytes", 50*(1<<20))

	if err := as.Parse(); err != nil {
		panic(err)
	}

	return Config{
		Port:         as.GetInt("p"),
		DBURI:        as.GetString("dburi"),
		FilePrefix:   as.GetString("fileprefix"),
		FileRoot:     as.GetString("fileroot"),
		Database:     as.GetString("database"),
		DriverType:   as.GetString("drivertype"),
		Auth:         as.GetBool("auth"),
		AuthLifetime: as.GetDuration("authlifetime"),
		MaxFileSize:  int64(as.GetInt("max-file-size")),
	}
}
