package testlogger

import (
	"runtime"
	"strings"
	"testing"
)

// This allows normal log messages to be redirected to the testing logger
// so that messages only show if the test fails. When not testing, the same messages
// can be sent to normal log destination.
type LogInf interface {
	Printf(format string, args ...interface{})
	Println(args ...interface{})
}

var Logger LogInf

type TestLogger struct {
	testing *testing.T
}

func NewTestLogger(t *testing.T) *TestLogger {
	return &TestLogger{t}
}

func (t *TestLogger) Printf(format string, args ...interface{}) {
	fname := ""
	pc, _, _, ok := runtime.Caller(1)
	if ok {
		fn := runtime.FuncForPC(pc)
		fname = fn.Name()
		ss := strings.SplitAfter(fname, "/")
		fname = ss[len(ss)-1] + ": "
	}

	t.testing.Logf(fname+format, args...)
}

func (t *TestLogger) Println(args ...interface{}) {
	fname := ""
	pc, _, _, ok := runtime.Caller(1)
	if ok {
		fn := runtime.FuncForPC(pc)
		fname = fn.Name()
		ss := strings.SplitAfter(fname, "/")
		var v interface{}
		v = ss[len(ss)-1] + ":"
		a := []interface{}{v}
		args = append(a, args...)
	}

	t.testing.Log(args...)
}
