package server

import (
	"fmt"
	"log"
	"strconv"
	"strings"
)

// Rewrite to become a general input handler
func (server *Server) readMessages(agent Agent) {
	for {
		_, message, err := agent.conn.ReadMessage()
		if err != nil {
			log.Println("Error reading message:", err)
			break
		}
		// log.Printf("Received(%d): %s\n", messageType, message)

		msgs := server.parseMessage(message)

		if msgs[0] == "update" {
			cpu_usg, err := strconv.Atoi(msgs[1])
			if err != nil {
				fmt.Println("ERROR: converting string to int", err)
			}
			server.Agents[agent.Name].Cpu = append(server.Agents[agent.Name].Cpu, cpu_usg)
			server.Agents[agent.Name].Cpu = server.pruneIntSlice(server.Agents[agent.Name].Cpu)

			mem_usg_string := strings.ReplaceAll(msgs[2], "GB", "")
			mem_usg_float, err := strconv.ParseFloat(mem_usg_string, 64)
			if err != nil {
				log.Fatal("ERROR: failed strconv.ParseFloat():", err)
			}
			server.Agents[agent.Name].Mem_usg = append(server.Agents[agent.Name].Mem_usg, mem_usg_float)
			server.Agents[agent.Name].Mem_usg = server.pruneFloat64Slice(server.Agents[agent.Name].Mem_usg)

			taskId, err := strconv.Atoi(msgs[3])
			if err != nil {
				log.Println("ERROR: cannot convert taskId:", err)
			}
			server.Agents[agent.Name].TaskId = taskId
		}

		if msgs[0] == "deregister" {
			server.closeConnection(agent.Name)
		}

		// This sets the time-out for any incoming messages.
		// conn.SetReadDeadline(time.Now().Add(10 * time.Second))
	}
}
