package backend

import (
	"os"
	"path/filepath"
	"encoding/json"
	"errors"
	"fmt"
	"git.noctra.dev/noctra/servtex/globals"
)

// Helper for configReader() that does the actual reading
func configReaderParse(filePath string, configOptionStorage *globals.Config) error {
	jsonData, err := os.ReadFile(filePath)
	if err == nil {
		err = json.Unmarshal(jsonData, &configOptionStorage)
		if err != nil { 
			// log error unmarshal failure
			return errors.New("Config file could not be read")
		}
	} else {
		return errors.New("Config file does not exist")
	}

	return nil
}

// Reads config file and stores the options in configOptionStorage
// Tries executable/path/configFileName
//	 %LOCALAPPDATA%\servtex\configFileName
//	 ~/.config/servtex/configFileName
func ConfigReader(configFileName string, configOptionStorage *globals.Config) error {
	exePath, err := os.Executable()
	if err == nil {
		path := filepath.Join(filepath.Dir(exePath), configFileName)
		err = configReaderParse(path, configOptionStorage)
		if err == nil { return nil }
	}

	localappdata := os.Getenv("LOCALAPPDATA")
	if localappdata != "" {
		path := filepath.Join(localappdata, "servtex", configFileName)
		err = configReaderParse(path, configOptionStorage)
		if err == nil { return nil }
	}

	path := filepath.Join("~", ".config", "servtex", configFileName)
	err = configReaderParse(path, configOptionStorage)
	if err == nil { return nil }

	// log error no config file found
	return errors.New("Configuration file not found or json parsing error")
}

// Watches a specified directory and calls a function on change
// Optionally, a minimum time to wait for consecutive changes can be specified
func ChangeWatch(path string, callOnChange func()) {
}

// Intended to be run as goroutine
func LatexCompile(config *globals.Config) error {
	if !config.ExecutionLock.TryLock() {
		return errors.New("Execution already in progress")
	}

	var latexCommand string
	switch config.LatexEngine {
		case "lualatex":
		latexCommand = fmt.Sprintf(
			"lualatex -output-directory=%s -jobname=servtex %s",
			config.LatexOutputPath,
			config.LatexSourceFilePath,
		)

	}
	
	fmt.Sprintf(latexCommand) // placeholder for compilation
	config.ExecutionLock.Unlock()
	return nil
}

