package main

import (
	"strconv"
	"strings"
	"testing"
	"time"
)

func TestValidTxid(t *testing.T) {
	tests := []struct {
		Txid  string
		Valid bool
	}{
		{Txid: "", Valid: false},
		{Txid: "1234567812345678123456781234567", Valid: false},
		{Txid: "12345678123456781234567812345678", Valid: true},
		{Txid: "123456781234567812345678123456789", Valid: false},
		{Txid: "1234567812345678123456781234567a", Valid: true},
		{Txid: "1234567812345678123456781234567A", Valid: false},
	}

	for _, tt := range tests {
		if have, want := validTxid(tt.Txid), tt.Valid; have != want {
			t.Errorf("validTxid(%q); %t != %t", tt.Txid, have, want)
		}
	}
}

func BenchmarkValidTxid(b *testing.B) {
	for i := 0; i < b.N; i++ {
		validTxid("12345678abcdef12345678abcdef")
	}
}

func TestIndexLogfmt(t *testing.T) {
	buf := makeKey()

	var key indexKey

	err := key.parse(buf)
	if err != nil {
		t.Fatalf("parse; err = %s", err)
	}

	if have, want := key.Index, true; have != want {
		t.Errorf("key.Index; %t != %t", have, want)
	}
	if have, want := key.Svcname, "svc"; have != want {
		t.Errorf("key.Svcname; %q != %q", have, want)
	}
	if have, want := key.Time, "1970-01-01T00:00:00.000000000Z"; have != want {
		t.Errorf("key.Time; %q != %q", have, want)
	}
	if have, want := key.Txid, "dddddddddddddddddddddddddddddddd"; have != want {
		t.Errorf("key.Txid; %q != %q", have, want)
	}
	if have, want := key.Path, ".1.6"; have != want {
		t.Errorf("key.Path; %q != %q", have, want)
	}
}

func BenchmarkIndexLogfmt(b *testing.B) {
	buf := makeKey()

	for i := 0; i < b.N; i++ {
		var key indexKey
		key.parse(buf)
	}
}

func makeKey() []byte {
	var key []byte

	key = append(key, "index"...)
	key = strconv.AppendQuote(append(key, " svcname="...), "svc")
	if false {
		key = strconv.AppendQuote(append(key, " host="...), "fqdn")
		key = strconv.AppendInt(append(key, " pid="...), int64(42), 10)
	}
	key = strconv.AppendQuote(append(key, " time="...),
		time.Unix(0, 0).UTC().Format("2006-01-02T15:04:05.000000000Z07:00"))
	key = strconv.AppendQuote(append(key, " txid="...), strings.Repeat("d", 32))
	key = strconv.AppendQuote(append(key, " path="...), ".1.6")

	return key
}
