package config

import (
	"flag"
	"fmt"

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

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

	flag.Usage = utils.Usage

	flag.StringVar(&configfile, "configfile", "qrz.ini", "config file to use with qrz section")
	flag.IntVar(&port, "port", 8080, "web port to use")
	flag.BoolVar(&nofeed, "nofeed", false, "no feed database table with entries at first launch")
	flag.Parse()

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

	qrzsection := cfg.Section("qrz")

	config.Port = port
	config.NoFeed = nofeed
	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.Cron = qrzsection.Key("cron").MustString("@every 1h")

	config.DbSchema = fmt.Sprintf(`
		CREATE TABLE IF NOT EXISTS %[1]s (
			id serial NOT NULL PRIMARY KEY,
			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,
			dmrid varchar(25) DEFAULT NULL,
			fts tsvector NULL,
			CONSTRAINT qrz_unique UNIQUE(qrz, name, city, dept, country)
		);

		CREATE INDEX IF NOT EXISTS fts_idx ON %[1]s (fts);

		CREATE OR REPLACE FUNCTION updateFTS() RETURNS trigger AS $fts_trigger$
			BEGIN
				IF pg_trigger_depth() <> 1 THEN
        			RETURN NEW;
    			END IF;
				UPDATE %[1]s SET fts = to_tsvector(concat_ws(' ', qrz, name, city, dept, country)) WHERE id = NEW.id;
				RETURN NEW;
			END;
		$fts_trigger$ LANGUAGE plpgsql;

		DROP TRIGGER IF EXISTS fts_trigger ON %[1]s;

		CREATE TRIGGER fts_trigger
			AFTER INSERT ON %[1]s
			FOR EACH ROW EXECUTE PROCEDURE updateFTS();
		`,
		config.DbTable)

	config.DbStatements.Insert = fmt.Sprintf(`
		INSERT INTO %[1]s (qrz, dmrid, name, city, dept, country)
		VALUES ($1, $2, $3, $4, $5, $6);
		`,
		config.DbTable)

	config.DbStatements.ExportCSV = fmt.Sprintf(`
		SELECT qrz, name, city, dept, country
		FROM %[1]s;
		`,
		config.DbTable)

	config.DbStatements.Countries = fmt.Sprintf(`
		SELECT country
		FROM %[1]s
		GROUP BY country;
		`,
		config.DbTable)

	config.URLBase = `http://groupe-frs.hamstation.eu/index_qrz_liste_%s.php`

	config.QrzGroups = []string{"01", "03", "09", "103", "104", "107", "119", "13", "14", "146", "147", "15", "156", "16", "161", "163", "18", "188", "2", "214", "233", "25", "26", "29", "30", "31", "32", "34", "43", "44", "49", "54", "64", "66", "76", "79", "84", "97", "98"}
	//config.QrzGroups = map[string]string{"France": "14"}

	return nil
}

// Config is the global config of qrz
type Config struct {
	Db *sqlx.DB

	DbHostname   string
	DbName       string
	DbUsername   string
	DbPassword   string
	DbSchema     string
	DbTable      string
	DbStatements struct {
		Insert    string
		ExportCSV string
		Countries string
	}
	URLBase   string
	QrzGroups []string
	Cron      string
	Port      int
	NoFeed    bool
	Version   string
}
