package main

/*
fn fetch_python_location() -> String {
	let output = Command::new("which python")
		.output()
		.expect("Failed to execute command");
	let output = String::from_utf8_lossy(&output.stdout);
	output.trim().to_string()
	output
}
*/
import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/gorilla/websocket"
)

const (
	WS_HOST = "0.0.0.0"
	WS_PORT = 5000
)

var Upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

func main() {
	http.HandleFunc("/", HandleWs)

	// output handlers
	http.HandleFunc("/lang", HandleLang)

	// if ./workspace/ directory does not exist, create it
	if _, err := os.Stat("./workspace/"); os.IsNotExist(err) {
		os.Mkdir("./workspace/", 0755)
	}

	addr := fmt.Sprintf("%s:%d", WS_HOST, WS_PORT)
	log.Println("Server started at", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}

func HandleWs(w http.ResponseWriter, r *http.Request) {
	log.Println("[/] Connection from", r.RemoteAddr)
	c, err := Upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		// get the first line of the message from the client
		_, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		// print the message to the console
		log.Printf("recv: %s", message)

		// seperate message into chunks by newline
		msg := strings.Split(string(message), "\n")
		handleCase(msg[0], strings.Join(msg[1:], "\n"))

		c.WriteMessage(websocket.TextMessage, []byte("Forwarding to output handler: "+msg[0]+"\n"))
	}
}

func HandleLang(w http.ResponseWriter, r *http.Request) {
	log.Println("[/lang] Connection from", r.RemoteAddr)
	// upgrade the connection to a websocket
	c, err := Upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}
	// defer c.Close()
	c.WriteMessage(websocket.TextMessage, []byte("Connected to output handler"))
	go func() {
		for {
			// wait for message from client
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("Error reading from client", err)
				break
			}
			// convert message to string
			msg := string(message)
			log.Println("Received message from client:", msg)
			// convert pyReader to string
			newstr := make([]byte, 1024)
			n, err := pyReader.Read(newstr)
			if err != nil {
				log.Println("Error reading from pyReader")
				break
			}
			c.WriteMessage(websocket.TextMessage, newstr[:n])
		}
	}()
}
