package chitin

import (
	"fmt"

	"code.justin.tv/common/chitin/internal/trace"

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

// printf writes a Context-enhanced log line. If ctx comes from a Context-
// enhanced http server, the log line is sent to the server's ErrorLog if it
// exists. The log lines end up at package log's standard logger otherwise.
//
// The log lines are prefixed with the Trace transaction id and Trace span id.
func printf(ctx context.Context, format string, v ...interface{}) {
	record(ctx, textEvent{logfmt: fmt.Sprintf(format, v...)})
}

type recorder interface {
	record(ctx context.Context, ev event)
}

type loggerFunc func(format string, v ...interface{})

func (l loggerFunc) record(ctx context.Context, ev event) {
	prefix := trace.Logfmt(ctx)
	l("%s %s", prefix, ev.Logfmt())
}

func record(ctx context.Context, ev event) {
	if r, ok := ctx.Value(keyRecorder).(recorder); ok {
		r.record(ctx, ev)
	}
}

type event interface {
	Logfmt() string
}

type textEvent struct {
	logfmt string
}

func (ev textEvent) Logfmt() string { return ev.logfmt }
