package server

import (
	"fmt"
	"net"
	"testing"
	"time"
)

const (
	testUDPHost = "127.0.0.1:5638"
)

type testUDPEchoHandler struct{}

func (a testUDPEchoHandler) Handler(conn *net.UDPConn) {
	buf := make([]byte, 1024)
	for {
		len, addr, err := conn.ReadFromUDP(buf)
		if err != nil {
			fmt.Println(err)
			continue
		}
		strData := string(buf)
		fmt.Println("Received:", strData)
		len, err = conn.WriteToUDP(buf[:len], addr)
		if err != nil {
			fmt.Println(err)
		}
	}
}
func validateUDPServer(t *testing.T, addr string) {
	cli, err := net.Dial("udp", testUDPHost)
	if err != nil {
		t.Fatal(err)
	}
	_, err = cli.Write([]byte(testEchoData))
	if err != nil {
		t.Fatal(err)
	}
	buf := make([]byte, 1024)
	length, err := cli.Read(buf)
	if err != nil {
		t.Fatal(err)
	}
	gotData := string(buf[:length])
	if gotData != testEchoData {
		t.Errorf("echo server test failed. want: %s, got: %s", testEchoData, gotData)
	}
}
func TestUDPServer(t *testing.T) {
	initLog("test", "debug")
	h := testUDPEchoHandler{}
	svr := &UDPServer{
		addr:    testUDPHost,
		handler: h,
	}
	err := svr.Start()
	if err != nil {
		t.Fatal(err)
	}
	time.Sleep(time.Millisecond * 100)
	validateUDPServer(t, testUDPHost)
}
