package engine

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"

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

func findUnrealVersionPath(version string) (string, error) {
	//Attempting to build project files programattically
	k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\EpicGames\Unreal Engine\`+version, registry.QUERY_VALUE)
	if err != nil {
		return "", err
	}
	defer k.Close()
	s, _, err := k.GetStringValue("InstalledDirectory") //Pulling the (Default) value which has the path
	if err != nil {
		return "", err
	}
	return s, nil
}

func buildProject(version string, projectABSPath string) error {
	unrealVersionPath, err := findUnrealVersionPath(version)
	if err != nil {
		fmt.Printf("Unable to find the path to Unreal Engine version %s, please build project files manually: %s ", version, err)
		bufio.NewReader(os.Stdin).ReadBytes('\n')
		os.Exit(1)
	}
	unrealVersionPath = unrealVersionPath + string(filepath.Separator) + "Engine" + string(filepath.Separator) + "Build" + string(filepath.Separator) + "BatchFiles" + string(filepath.Separator) + "Build.bat"
	checkPath(unrealVersionPath) // Verifying path, will exit if fail
	fmt.Println("Using Unreal Engine Path: ", unrealVersionPath)
	// Manually building up the commmand
	buildArgs := []string{"Development", "Win64", "-Project=" + projectABSPath, "-TargetType=Editor", "-Progress", "-NoEngineChanges", "-NoHotReloadFromIDE"}
	buildFilesCMD := exec.Command(unrealVersionPath, buildArgs...)
	// Making sure we write the output of the command to the command prompt
	out := io.Writer(os.Stdout)
	buildFilesCMD.Stdout = out
	// finally running the command
	err = buildFilesCMD.Run()
	if err != nil {
		return err
	}
	return nil
}
