package engine

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strings"

	"golang.org/x/sys/windows/registry"
)

func findUnrealPath() (string, error) {
	//Attempting to generate project files programattically
	k, err := registry.OpenKey(registry.CLASSES_ROOT, `Unreal.ProjectFile\DefaultIcon`, registry.QUERY_VALUE)
	if err != nil {
		return "", err
	}
	defer k.Close()
	s, _, err := k.GetStringValue("") //Pulling the (Default) value which has the path
	if err != nil {
		return "", err
	}
	s = strings.Trim(s, "\"") //Trim the quotes from around the string
	return s, nil
}

func generateFiles(projectFileABSPath string) error {
	// find the path to versionswitcher which is not in a specific unreal version directory since it needs to switch between versions
	unrealExPath, err := findUnrealPath()
	if err != nil {
		fmt.Println("Unable to find the path to Unreal engine, please generate project files manually: ", err)
		bufio.NewReader(os.Stdin).ReadBytes('\n')
		os.Exit(1)
	}
	checkPath(unrealExPath) // Verifying path, will exit if fail
	fmt.Println("Using Unreal Engine Path: ", unrealExPath)
	generateArgs := []string{"/projectfiles", projectFileABSPath}
	generateFilesCMD := exec.Command(unrealExPath, generateArgs...)
	// var stdBuffer bytes.Buffer
	// mw := io.MultiWriter(os.Stdout, &stdBuffer)
	out := io.Writer(os.Stdout)
	generateFilesCMD.Stdout = out
	err = generateFilesCMD.Run()
	if err != nil {
		return err
	}
	return nil
}
