package trace

import (
	"net/http"
	"reflect"
	"testing"

	"golang.org/x/net/context"
)

func TestHeader(t *testing.T) {
	h := testHeaders()
	ctx := ContextFromHeader(context.Background(), h)

	if have, want := ctx.Value(keyTransaction).(*transaction).TxID, [2]uint64{12345, 9}; have != want {
		t.Errorf("transaction id; %d != %d", have, want)
	}
	if have, want := ctx.Value(keyTransaction).(*transaction).Path, (callPath{6, 7, 8}); !reflect.DeepEqual(have, want) {
		t.Errorf("span id; %q != %q", have, want)
	}

	out1 := make(http.Header)
	AugmentHeader(ctx, out1)
	if have, want := out1[http.CanonicalHeaderKey("Trace-ID")], []string{"12345", "9"}; !reflect.DeepEqual(have, want) {
		t.Errorf("Trace-ID; %q != %q", have, want)
	}
	if have, want := out1.Get("Trace-Span"), ".6.7.8"; have != want {
		t.Errorf("Trace-Span; %q != %q", have, want)
	}

	out2 := make(http.Header)
	child := ctx
	for i := 0; i < 24+1; i++ {
		child = NewSpan(ctx)
	}
	AugmentHeader(child, out2)
	if have, want := out2[http.CanonicalHeaderKey("Trace-ID")], []string{"12345", "9"}; !reflect.DeepEqual(have, want) {
		t.Errorf("Trace-ID; %q != %q", have, want)
	}
	if have, want := out2.Get("Trace-Span"), ".6.7.8.24"; have != want {
		t.Errorf("Trace-Span; %q != %q", have, want)
	}
}

func TestNonZero(t *testing.T) {
	suspect := 0
	count := 20
	for i := 0; i < count; i++ {
		h := make(http.Header)
		ctx := ContextFromHeader(context.Background(), h)
		txid := ctx.Value(keyTransaction).(*transaction).TxID

		if txid[0] == 0 || txid[1] == 0 {
			suspect++
		}
	}

	if suspect >= 5 {
		t.Errorf("TxID is often unset (%d times out of %d)", suspect, count)
	}
}

func TestLogfmt(t *testing.T) {
	h := testHeaders()
	ctx := ContextFromHeader(context.Background(), h)

	if have, want := Logfmt(ctx), "trace-id=12345,9                                   trace-span=\".6.7.8\""; have != want {
		t.Errorf("Logfmt;\n%q\n!=\n%q", have, want)
	}
}

func testHeaders() http.Header {
	h := make(http.Header)
	h.Set("Trace-ID", "12345")
	h.Add("Trace-ID", "9")
	h.Set("Trace-Span", ".6.7.8")
	return h
}
