package main

import (
	"encoding/json"
	"errors"
	"io/fs"

	"fmt"
	"os"

	"github.com/adhocore/jsonc"
	// "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:     60,
		Cache:        ".gopaper",
	}
}

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

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

	configDir := homeDir + "/.config/gopaper/"
	configRaw, readError := os.ReadFile(configDir + "config.jsonc")
	if readError != nil && errors.Is(readError, fs.ErrNotExist) {
		defaultConfig := makeDefaultConfig()
		defaultConfigJSON, err := json.MarshalIndent(defaultConfig, "", "")
		if err != nil {
			elog.Println("could not encode default config!")
			return err
		}

		err = os.Mkdir(homeDir+"/.config", 774)
		if err != nil && !os.IsExist(err) {
			elog.Println("could not create .config directory", err)
			return err
		}

		err = os.Mkdir(configDir, 774)
		if err != nil && !os.IsExist(err) {
			elog.Println("could not create .config/gopaper directory")
			return err
		}

		file, err := os.Create(configDir + "config.jsonc")
		defer file.Close()
		if err != nil {
			elog.Println("could not create config file!")
			return err
		}
		file.Write(defaultConfigJSON)
		*config = defaultConfig
	}

	if readError == nil {
		configRaw = j.Strip(configRaw)
		err = json.Unmarshal(configRaw, &config)
		if err != nil {
			elog.Println("Couldn't unmarshal config!")
			return 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 + "/"
	return nil
}
