package clog

import (
	"bytes"
	"fmt"
	"log"
	"math"
	"strings"
	"testing"

	"code.justin.tv/common/chitin/internal/trace"
	"golang.org/x/net/context"
)

func TestBase(t *testing.T) {
	maxTxidLen := len(fmt.Sprintf("%d,%d", uint64(math.MaxUint64), uint64(math.MaxUint64)))

	backgroundPrefix := fmt.Sprintf("trace-id=%-*s trace-span=%q ", maxTxidLen, "0,0", "")

	var buf1 bytes.Buffer
	log.SetOutput(&buf1)
	log.SetFlags(0)
	Log(context.Background()).Printf("hello %s", "world")
	if have, want := buf1.String(), backgroundPrefix+"hello world\n"; have != want {
		t.Errorf("Log(context.Background()).Printf; %q != %q", have, want)
	}

	var buf2 bytes.Buffer
	lg := log.New(&buf2, "", 0)
	Log(
		context.Background(),
		SetConsumer(func(s string) { lg.Print(s) }),
	).Printf("hi %s", "there")
	if have, want := buf2.String(), backgroundPrefix+"hi there\n"; have != want {
		t.Errorf("Log(context.Background()).Printf; %q != %q", have, want)
	}

	var buf3 bytes.Buffer
	lg = log.New(&buf3, "", 0)
	Log(
		trace.ContextFromHeader(context.Background(), nil),
		SetConsumer(func(s string) { lg.Print(s) }),
	).Printf("ahoy %s", "matey")
	if have, want := buf3.String(), "trace-id="; !strings.HasPrefix(have, want) {
		t.Errorf("Log(ctx).Printf; !strings.HasPrefix(%q, %q)", have, want)
	}
	if have, want := buf3.String(), " trace-span=\"\" ahoy matey\n"; !strings.HasSuffix(have, want) {
		t.Errorf("Log(ctx).Printf; !strings.HasSuffix(%q, %q)", have, want)
	}
}
