package trace_test

import (
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"

	"code.justin.tv/common/chitin"
	"code.justin.tv/common/chitin/internal/trace"
	"code.justin.tv/release/trace/pbmsg"
	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"
)

type packetWriter struct {
	contents [][]byte
}

func (pw *packetWriter) Write(p []byte) (int, error) {
	ours := append(make([]byte, 0, len(p)), p...)
	pw.contents = append(pw.contents, ours)
	return len(p), nil
}

func TestSend(t *testing.T) {
	const count = 20

	var pw packetWriter

	ctx, err := trace.WithInfo(context.Background(), trace.SetDestination(&pw))
	if err != nil {
		t.Fatalf("trace.WithInfo; err = %v", err)
	}

	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	}))
	srv.Config.Handler = chitin.Handler(srv.Config.Handler, chitin.SetBaseContext(ctx))
	srv.Start()

	var wg sync.WaitGroup
	for i := 0; i < count; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, err := http.Get(srv.URL)
			if err != nil {
				t.Errorf("http.Get; err = %v", err)
			}
			defer resp.Body.Close()
		}()
	}
	wg.Wait()

	srv.Close()

	if t.Failed() {
		t.FailNow()
	}

	var events []*pbmsg.Event
	for _, buf := range pw.contents {
		set := new(pbmsg.EventSet)
		err := proto.Unmarshal(buf, set)
		if err != nil {
			t.Errorf("proto.Unmarshal; err = %v", err)
		}
		events = append(events, set.Event...)
	}

	if have, want := len(events), 2; have < want {
		t.Fatalf("len(events); %d < %d", have, want)
	}

	txids := make(map[[2]uint64]struct{})
	for _, ev := range events {
		if have, want := len(ev.TransactionId), 2; have != want {
			t.Errorf("len(ev.TransactionId); %d != %d", have, want)
			continue
		}
		txids[[2]uint64{ev.TransactionId[0], ev.TransactionId[1]}] = struct{}{}
	}

	if have, want := len(txids), count; have != want {
		t.Errorf("len(txids); %d != %d", have, want)
	}

	if _, ok := txids[[2]uint64{0, 0}]; ok {
		t.Errorf("transaction id is zero")
	}
}
