package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/adhocore/jsonc"
)

type Config struct {
	ImageFilters ImageFilters
	ImagesDir    string
	Duration     int
	Cache        string
	Default      string
}

func makeDefaultConfig() Config {
	ImageFilters := makeDefaultImageFilters()
	return Config{
		ImageFilters: ImageFilters,
		ImagesDir:    "bgs",
		Duration:     1,
		Cache:        ".gopaper",
	}
}

func (config *Config) load() {
	j := jsonc.New()

	homeDir, err := os.UserHomeDir()
	if err != nil {
		log.Fatal("could not get home directory!", err)
	}

	configPath := homeDir + "/.config/gopaper/config.jsonc"
	configRaw, err := os.ReadFile(configPath)
	if err != nil {
		if !os.IsExist(err) {
			defaultConfig := makeDefaultConfig()
			defaultConfigJSON, err := json.MarshalIndent(defaultConfig, "", "")
			if err != nil {
				log.Fatal("could not encode default config!", err)
			}
			file, err := os.Create(configPath)
			defer file.Close()
			if err != nil {
				log.Fatal("could not create config file!", err)
			}
			file.Write(defaultConfigJSON)
			*config = defaultConfig
		}
	} else {

		configRaw = j.Strip(configRaw)
		err = json.Unmarshal(configRaw, &config)
		if err != nil {
			log.Fatal("Couldn't unmarshal config!\n", err)
		}

	}

	config.Cache = homeDir + "/" + config.Cache + "/"
	//make directory if it doesn't exist
	_, err = os.Stat(config.Cache)
	if os.IsNotExist(err) {
		fmt.Printf("Cache directory %v not found. Making one.\n", config.Cache)
		os.Mkdir(config.Cache, 0777)
	}

	config.ImagesDir = homeDir + "/" + config.ImagesDir + "/"
}
