package config

import (
	"flag"
	"fmt"

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

// GetConfig fetch configuration
func (config *Config) GetConfig() error {
	var configfile string

	flag.Usage = utils.Usage

	flag.StringVar(&configfile, "configfile", "qrz.ini", "config file to use with qrz section")
	flag.Parse()

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

	qrzsection := cfg.Section("qrz")

	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.DbSchema = qrzsection.Key("db_schema").MustString("")
	config.DbTable = qrzsection.Key("db_table").MustString("qrz")
	config.FrsConfig.URL = qrzsection.Key("frs_url").MustString("")
	config.FrsConfig.XPath = qrzsection.Key("frs_xpath").MustString("//tr")
	config.FrsConfig.Regex = qrzsection.Key("frs_regex").MustString(".*")

	config.DbSchema = fmt.Sprintf("CREATE TABLE IF NOT EXISTS `%s` (`id` int(8) NOT NULL AUTO_INCREMENT, `qrz` varchar(25) NOT NULL, `name` varchar(25) DEFAULT NULL, `address` varchar(50) DEFAULT NULL,  `city` varchar(50) DEFAULT NULL, `zipcode` varchar(5) DEFAULT NULL, `dept` varchar(50) DEFAULT NULL, `country` varchar(25) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `qrz` (`qrz`,`name`,`city`,`dept`) USING BTREE,  KEY `test` (`country`), FULLTEXT KEY `city` (`city`), FULLTEXT KEY `dept` (`dept`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;", config.DbTable)

	config.Statements.DbInsert = "INSERT IGNORE INTO %s (qrz,name,city,dept,country) VALUES ('%s','%s','%s','%s','%s');"

	config.Statements.DbGetQrz = "SELECT qrz FROM %s;"

	config.Statements.DbCheck = "SELECT COUNT(*) FROM %s WHERE qrz = '%s';"

	return nil
}

// Config is the global config of g2g
type Config struct {
	DbHostname string
	DbName     string
	DbUsername string
	DbPassword string
	DbSchema   string
	DbTable    string
	Statements struct {
		DbInsert string
		DbGetQrz string
		DbCheck  string
	}
	FrsConfig struct {
		URL   string
		XPath string
		Regex string
	}
}
