package server

import (
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// Handle incoming websocket connections
func (server *Server) handleConnections(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}
	// defer conn.Close()

	log.Println("Incoming connection")

	// Check for register
	var registered bool
	var msgs []string
	for !registered {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("Error reading message:", err)
			break
		}

		msgs = server.parseMessage(message)
		if string(msgs[0]) == "register" {
			registered = true
		}
	}
	log.Println("Connected to agent")

	// Create var of type Agent
	cores_int, err := strconv.Atoi(msgs[2])
	if err != nil {
		log.Fatal("ERROR: failed strconv.Atoi(cpu cores):", err)
	}
	mem_max_string := strings.ReplaceAll(msgs[3], "GB", "")
	mem_max_float, err := strconv.ParseFloat(mem_max_string, 64)
	if err != nil {
		log.Fatal("ERROR: failed strconv.ParseFloat():", err)
	}
	agent := Agent{
		Name:    msgs[1],
		Reg:     time.Now(),
		Cores:   cores_int,
		Mem_max: mem_max_float,
		TaskId:  0,
		conn:    conn,
	}

	// Dump it into server.Agents
	server.Agents[msgs[1]] = &agent

	defer server.closeConnection(msgs[1])

	go server.readMessages(agent)
	server.writeMessages(conn)

}
