package config

import (
	"flag"

	"git.paulbsd.com/paulbsd/qrz/utils"
	"gopkg.in/ini.v1"
	"xorm.io/xorm"
)

// GetConfig fetch configuration
func (config *Config) GetConfig() error {
	var configfile string
	var nofeed bool
	var debug bool
	var host string
	var port int

	flag.Usage = utils.Usage

	flag.StringVar(&configfile, "configfile", "qrz.ini", "config file to use with qrz section")
	flag.StringVar(&host, "host", "[::]", "http host to bind to")
	flag.IntVar(&port, "port", 8087, "http port to use")
	flag.BoolVar(&nofeed, "nofeed", false, "do not feed table with entries at first launch")
	flag.BoolVar(&debug, "debug", false, "enable debug")
	flag.Parse()

	cfg, err := ini.Load(configfile)
	if err != nil {
		return err
	}

	qrzsection := cfg.Section("qrz")

	config.Host = host
	config.Port = port
	config.NoFeed = nofeed
	config.Debug = debug
	config.DbType = qrzsection.Key("db_type").MustString("postgres")
	config.DbHostname = qrzsection.Key("db_hostname").MustString("localhost")
	config.DbName = qrzsection.Key("db_name").MustString("database")
	config.DbUsername = qrzsection.Key("db_username").MustString("username")
	config.DbPassword = qrzsection.Key("db_password").MustString("password")
	config.Cron = qrzsection.Key("cron").MustString("@every 1h")

	config.URLBase = `https://groupe-frs.hamstation.eu/index_qrz_liste_%s.php`
	config.URLBaseForGroups = "https://groupe-frs.hamstation.eu/bdd/menu_listing_division.php"

	config.QrzGroups = []string{}

	return nil
}

// Config is the global config of qrz
type Config struct {
	Db               *xorm.Engine
	DbType           string
	DbHostname       string
	DbName           string
	DbUsername       string
	DbPassword       string
	URLBase          string
	URLBaseForGroups string
	QrzGroups        []string
	Cron             string
	Host             string
	Port             int
	NoFeed           bool
	Debug            bool
	Version          string
}
