package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"os/signal"
	"time"

	"github.com/gorilla/websocket"
)

func main() {
	log.Println("Starting client...")
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	host := "127.0.0.1:5000"
	langURL := fmt.Sprintf("ws://%s/lang", host)
	cmdURL := fmt.Sprintf("ws://%s/cmd", host)
	debugURL := fmt.Sprintf("ws://%s/debug", host)
	execURL := fmt.Sprintf("ws://%s/", host)

	execConn, err := connectWebSocket(execURL)
	if err != nil {
		log.Fatal("Failed to connect to lang websocket:", err)
	}
	defer execConn.Close()

	langConn, err := connectWebSocket(langURL)
	if err != nil {
		log.Fatal("Failed to connect to lang websocket:", err)
	}
	defer langConn.Close()

	cmdConn, err := connectWebSocket(cmdURL)
	if err != nil {
		log.Fatal("Failed to connect to cmd websocket:", err)
	}
	defer cmdConn.Close()

	debugConn, err := connectWebSocket(debugURL)
	if err != nil {
		log.Fatal("Failed to connect to debug websocket:", err)
	}
	defer debugConn.Close()

	done := make(chan struct{})
	go readMessages(langConn, "lang", done)
	go readMessages(cmdConn, "cmd", done)
	go readMessages(debugConn, "debug", done)
	// Read the contents of source.txt
	sourceFile := "source.txt"
	sourceData, err := ioutil.ReadFile(sourceFile)
	if err != nil {
		log.Fatal("Failed to read source file:", err)
	}

	// create execConn off of / endpoint

	// BLAME COPILOT FOR THIS
	// Send the contents over the lang websocket
	sendSourceData := func() {
		err = execConn.WriteMessage(websocket.TextMessage, sourceData)
		if err != nil {
			log.Fatal("Failed to send source data over lang websocket:", err)
		}
	}

	sendSourceData()

	// Listen for space key press in console
	go func() {
		reader := bufio.NewReader(os.Stdin)
		for {
			char, _, err := reader.ReadRune()
			if err != nil {
				log.Fatal("Failed to read from console:", err)
			}

			if char == ' ' {
				sendSourceData()
			}
		}
	}()

	// Send the contents over the lang websocket
	err = execConn.WriteMessage(websocket.TextMessage, sourceData)
	if err != nil {
		log.Fatal("Failed to send source data over lang websocket:", err)
	}

	<-interrupt
	fmt.Println("Interrupt signal received, closing connections...")
	close(done)
	time.Sleep(1 * time.Second)
}

func connectWebSocket(urlStr string) (*websocket.Conn, error) {
	u, err := url.Parse(urlStr)
	if err != nil {
		return nil, err
	}

	conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		return nil, err
	}

	return conn, nil
}

func readMessages(conn *websocket.Conn, name string, done chan struct{}) {
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("Error reading message from", name, "websocket:", err)
			return
		}
		fmt.Printf("Received message from %s: %s\n", name, message)
	}
}
