package config

import (
	"log"
	"os"

	"github.com/BurntSushi/toml"
)

type Config struct {
	SiteName          string `toml:"site_name"`
	Port              string `toml:"port"`
	DataDir           string `toml:"data_dir"`
	AdminUser         string `toml:"admin_user"`
	AdminPasswordHash string `toml:"admin_password_hash"`
}

func Load(path string) Config {
	configData := Config{
		SiteName: "Unnamed Download Listing",
		Port:     ":8080",
		DataDir:  "data",
	}

	// Overwrite the default configuration (configData) with data from the file at 'path'
	_, err := toml.DecodeFile(path, &configData)
	if err != nil {
		log.Println("No config file found, using defaults. Consider setting up a Site Name at the very least!")
	}

	return configData
}

func Save(path string, configData Config) error {
	file, err := os.Create(path)
	if err != nil {
		log.Println("An error occured while trying to save configuration data.")
		return err
	}
	defer file.Close()

	file.WriteString("site_name = \"" + configData.SiteName + "\"\n")
	file.WriteString("port = \"" + configData.Port + "\"\n")
	file.WriteString("data_dir = \"" + configData.DataDir + "\"\n")

	if configData.AdminUser != "" {
		file.WriteString("admin_user = \"" + configData.AdminUser + "\"\n")
		file.WriteString("admin_password_hash = \"" + configData.AdminPasswordHash + "\"\n")
		file.WriteString("# This admin_password_hash above is a hashed password, not your actual\n")
		file.WriteString("# written password. You can't change your admin password here.\n")
		file.WriteString("# If you've lost your password, delete admin_user and admin_hash\n")
		file.WriteString("# from this file and restart the app to create a new account.\n")
		file.WriteString("# Your uploaded content will stay intact.\n")
	}

	return nil
}
