package clog

import (
	"bytes"
	"log"
	"strings"
	"testing"

	"code.justin.tv/rhys/nursery/xarth/internal/trace"
	"golang.org/x/net/context"
)

func TestBase(t *testing.T) {
	backgroundPrefix := "trace-id=" + strings.Repeat(" ", 18) + ` trace-span="" `

	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=0x"; !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)
	}
}
