package mihomoapi

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func TestTrafficRatesReadsFirstFrame(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		flusher, _ := w.(http.Flusher)
		_ = json.NewEncoder(w).Encode(TrafficRates{Up: 100, Down: 200})
		flusher.Flush()
		time.Sleep(2 * time.Second)
		_ = json.NewEncoder(w).Encode(TrafficRates{Up: 300, Down: 400})
		flusher.Flush()
	}))
	defer srv.Close()

	client := New(srv.URL, "")
	ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
	defer cancel()

	rates, err := client.TrafficRates(ctx)
	if err != nil {
		t.Fatalf("TrafficRates: %v", err)
	}
	if rates.Up != 100 || rates.Down != 200 {
		t.Fatalf("got %+v", rates)
	}
}
