package websocket_test

import (
	"encoding/json"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	wslib "github.com/gorilla/websocket"
	"github.com/user/nanometrics/server/websocket"
)

func TestHubBroadcast(t *testing.T) {
	hub := websocket.NewHub()
	srv := httptest.NewServer(websocket.Handler(hub))
	defer srv.Close()

	url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws"
	conn, _, err := wslib.DefaultDialer.Dial(url, nil)
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer conn.Close()

	time.Sleep(50 * time.Millisecond)

	hub.Broadcast(map[string]string{"type": "test", "msg": "hello"})

	conn.SetReadDeadline(time.Now().Add(time.Second))
	_, data, err := conn.ReadMessage()
	if err != nil {
		t.Fatalf("read: %v", err)
	}
	var got map[string]string
	json.Unmarshal(data, &got)
	if got["msg"] != "hello" {
		t.Errorf("attendu hello, eu %s", got["msg"])
	}
}
