package serialize

import (
	"reflect"
	"testing"

	"github.com/kr/logfmt"
)

func TestLogfmtRecode(t *testing.T) {
	start := new(talLogfmt)
	err := toLogfmt(start, golden)
	if err != nil {
		t.Fatalf("convert: %v", err)
	}

	buf, err := start.MarshalText()
	if err != nil {
		t.Fatalf("marshal: %v", err)
	}
	t.Logf("len: %d", len(buf))

	var end talLogfmt
	err = logfmt.Unmarshal(buf, &end)
	if err != nil {
		t.Fatalf("unmarshal: %v", err)
	}

	silver := new(talGolden)
	err = fromLogfmt(silver, &end)
	if err != nil {
		t.Fatalf("deconvert: %v", err)
	}

	if have, want := silver, golden; !reflect.DeepEqual(have, want) {
		t.Errorf("values don't match:\n%#v\n!=\n%#v", have, want)
	}
}

func BenchmarkLogfmtEncode(b *testing.B) {
	for i := 0; i < b.N; i++ {
		start := new(talLogfmt)
		err := toLogfmt(start, golden)
		if err != nil {
			b.Fatalf("convert: %v", err)
		}

		buf, err := start.MarshalText()
		if err != nil {
			b.Fatalf("marshal: %v", err)
		}
		if i == 0 {
			b.SetBytes(int64(len(buf)))
		}
	}
}

func BenchmarkLogfmtDecode(b *testing.B) {
	start := new(talLogfmt)
	err := toLogfmt(start, golden)
	if err != nil {
		b.Fatalf("convert: %v", err)
	}

	buf, err := start.MarshalText()
	if err != nil {
		b.Fatalf("marshal: %v", err)
	}
	b.SetBytes(int64(len(buf)))

	for i := 0; i < b.N; i++ {
		var end talLogfmt
		err := logfmt.Unmarshal(buf, &end)
		if err != nil {
			b.Fatalf("unmarshal: %v", err)
		}

		silver := new(talGolden)
		err = fromLogfmt(silver, &end)
		if err != nil {
			b.Fatalf("deconvert: %v", err)
		}
	}
}
