package scanproto

import (
	"testing"
	"time"

	"code.justin.tv/release/trace/api"
	"code.justin.tv/release/trace/pbmsg"
)

type fixedSource struct {
	txs  chan *api.Transaction
	errs chan error
}

func (f *fixedSource) Run() {}

func (f *fixedSource) Stop() {}

func (f *fixedSource) Transactions() <-chan *api.Transaction { return f.txs }

func (f *fixedSource) Errors() <-chan error { return f.errs }

func TestLegacySource(t *testing.T) {
	s := &fixedSource{
		txs:  make(chan *api.Transaction, 10),
		errs: make(chan error),
	}
	for i := 0; i < 3; i++ {
		s.txs <- &api.Transaction{}
	}
	close(s.txs)

	src := LegacySource(s)
	go src.Run()

	bail := time.NewTimer(1 * time.Second)
	defer bail.Stop()

	var txs []*pbmsg.Transaction

loop:
	for {
		select {
		case err := <-src.Errors():
			t.Errorf("src.Errors; err = %q", err)
			break loop
		case tx, ok := <-src.Transactions():
			if !ok {
				break loop
			}
			txs = append(txs, tx)
		case <-bail.C:
			t.Errorf("timed out")
			break loop
		}
	}

	if have, want := len(txs), 3; have != want {
		t.Errorf("len(txs); %d != %d", have, want)
	}
}
