package trace

import (
	"reflect"
	"testing"
	"time"
)

type packetWriter struct {
	contents [][]byte
}

func (pw *packetWriter) Write(p []byte) (int, error) {
	ours := append(make([]byte, 0, len(p)), p...)
	pw.contents = append(pw.contents, ours)
	return len(p), nil
}

func TestBatchWriter(t *testing.T) {
	var pw packetWriter
	lw := &lockWriter{w: &pw}
	bw := newBatchWriter(lw, 12)

	confirmLen := func(n int) {
		lw.mu.Lock()
		if have, want := len(pw.contents), n; have != want {
			t.Errorf("len(pw.contents); %d != %d", have, want)
		}
		lw.mu.Unlock()
	}

	bw.Write([]byte("hello world"))
	confirmLen(0)

	bw.Write([]byte("hi again..."))
	confirmLen(1)

	bw.Write([]byte("what's "))
	confirmLen(2)

	bw.Write([]byte("up??"))
	confirmLen(2)

	time.Sleep(2 * flushInterval)
	confirmLen(3)

	lw.mu.Lock()
	contents := [][]byte{
		[]byte("hello world"),
		[]byte("hi again..."),
		[]byte("what's up??"),
	}
	if have, want := pw.contents, contents; !reflect.DeepEqual(have, want) {
		t.Errorf("pw.contents; \n%q\n!=\n%q", have, want)
	}
	lw.mu.Unlock()
}
