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() error {
	j := jsonc.New()

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

	configDir := homeDir + "/.config/gopaper/"
	configRaw, err := os.ReadFile(configDir)
	if err != nil {
		if !os.IsExist(err) {
			defaultConfig := makeDefaultConfig()
			defaultConfigJSON, err := json.MarshalIndent(defaultConfig, "", "")
			if err != nil {
				log.Println("could not encode default config!")
				return err
			}
			//TODO: make parent directories if they don't exist
			err = os.Mkdir(homeDir+"/.config", 755)
			if err != nil && !os.IsExist(err) {
				log.Println("could not create .config directory", err)
				return err
			}
			err = os.Mkdir(configDir, 755)
			if err != nil && !os.IsExist(err) {
				log.Println("could not create .config/gopaper directory")
				return err
			}

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

		configRaw = j.Strip(configRaw)
		err = json.Unmarshal(configRaw, &config)
		if err != nil {
			log.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
}
