package main

import (
	"fmt"
	"log"
	"os/exec"
	"path/filepath"
	"strings"

	// import file writer
	"os"
	// import websocket
)

func handleCase(caseName, data string) string {
	caseName = strings.ReplaceAll(caseName, "\n", "")
	caseName = strings.ReplaceAll(caseName, "\r", "")
	caseName = strings.ReplaceAll(caseName, ":", "")

	log.Println("Handling case", caseName)
	switch caseName {
	case "python", "python3", "py":
		log.Println(data)
		runPython(data)
	default:
		fmt.Printf("caseName: %q\n", caseName)
		log.Println(data)
	}
	return ""
}

func runPython(data string) {
	log.Println("Running python")
	// create a file in the workspace directory
	f, err := os.Create("./workspace/main.py")
	if err != nil {
		log.Println("Error creating file")
		return
	}
	defer f.Close()

	// write the data to the file
	_, err = f.WriteString(data)
	if err != nil {
		log.Println("Error writing to file")
		return
	}

	// find python, python3, or py in the system
	fname, err := exec.LookPath("python3")
	if err != nil {
		log.Println("Python not found")
	} else {
		log.Println("Python found at", fname)
	}
	// fname := "C:\\Users\\zachd\\scoop\\shims\\python3.exe"

	// if main.py does not exist, return
	if _, err := os.Stat("./workspace/main.py"); os.IsNotExist(err) {
		log.Println("File does not exist")
		return
	}

	cmd := exec.Command(fname, "./main.py")
	cmd.Dir = filepath.ToSlash("./workspace/")

	cmd.Stdout = pyWriter
	cmd.Stderr = pyWriter

	// start the command
	cmd.Run()
	log.Println("Python runtime finished")
}
