package main

import (
	// External
	werr "git.ahall.se/go/wrappederror"
	"github.com/jackc/pgx/v5"

	// Standard
	"context"
	"time"
)

type Configuration struct {
	timezoneLocation *time.Location
	Settings         map[string]string
}

var smonConfig Configuration

func SmonConfigInit() (cfg Configuration, err error) {
	cfg.Settings = make(map[string]string, 8)

	var rows pgx.Rows
	rows, err = db.Query(context.Background(), `SELECT * FROM public.configuration`)
	if err != nil {
		err = werr.Wrap(err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var setting, value string
		err = rows.Scan(&setting, &value)
		if err != nil {
			err = werr.Wrap(err)
			return
		}

		cfg.Settings[setting] = value
	}

	err = cfg.LoadTimezone()
	return
}

func (cfg *Configuration) Validate() (err error) {
	mandatorySettings := []string{"THEME", "TIMEZONE"}
	for _, settingsKey := range mandatorySettings {
		if _, found := cfg.Settings[settingsKey]; !found {
			return werr.New("Configuration missing setting '%s' in database", settingsKey)
		}
	}
	return
}

func (cfg *Configuration) LoadTimezone() (err error) {
	cfg.timezoneLocation, err = time.LoadLocation(cfg.Settings["TIMEZONE"])
	return
}

func (cfg *Configuration) Timezone() *time.Location {
	return cfg.timezoneLocation
}

func (cfg *Configuration) SetTheme(theme string) (err error) {
	cfg.Settings["THEME"] = theme
	_, err = db.Exec(context.Background(), `UPDATE public.configuration SET value=$1 WHERE setting='THEME'`, theme)
	return
}

func (cfg *Configuration) SetTimezone(tz string) (err error) {
	cfg.Settings["TIMEZONE"] = tz
	err = cfg.LoadTimezone()
	if err != nil {
		return werr.Wrap(err).WithData(tz)
	}

	_, err = db.Exec(context.Background(), `UPDATE public.configuration SET value=$1 WHERE setting='TIMEZONE'`, tz)
	if err != nil {
		return werr.Wrap(err).WithData(tz)
	}

	return
}
