package transport_test

import (
	"encoding/json"
	"net"
	"testing"
	"time"

	"github.com/user/nanometrics/server/models"
	"github.com/user/nanometrics/server/transport"
)

func TestUDPReceive(t *testing.T) {
	received := make(chan *models.AgentMetrics, 1)
	err := transport.StartUDP("127.0.0.1:29999", func(m *models.AgentMetrics) {
		received <- m
	})
	if err != nil {
		t.Fatalf("start UDP: %v", err)
	}

	conn, err := net.Dial("udp", "127.0.0.1:29999")
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	cpu := 55.0
	m := models.AgentMetrics{Hostname: "test-01", IP: "127.0.0.1", Status: "online", CPUPercent: &cpu}
	data, _ := json.Marshal(m)
	conn.Write(data)

	select {
	case got := <-received:
		if got.Hostname != "test-01" {
			t.Errorf("hostname: attendu test-01, eu %s", got.Hostname)
		}
		if got.CPUPercent == nil || *got.CPUPercent != 55.0 {
			t.Error("cpu_percent incorrect")
		}
	case <-time.After(time.Second):
		t.Error("timeout: aucune métrique reçue")
	}
}
