package loser_test

import (
	"math"
	"testing"

	"github.com/bboreham/go-loser"
)

type List struct {
	list []uint64
	cur  uint64
}

func NewList(list ...uint64) *List {
	return &List{list: list}
}

func (it *List) At() uint64 {
	return it.cur
}

func (it *List) Next() bool {
	if len(it.list) > 0 {
		it.cur = it.list[0]
		it.list = it.list[1:]
		return true
	}
	it.cur = 0
	return false
}

func (it *List) Seek(val uint64) bool {
	for it.cur < val && len(it.list) > 0 {
		it.cur = it.list[0]
		it.list = it.list[1:]
	}
	return len(it.list) > 0
}

func checkIterablesEqual[E loser.Value, S1 loser.Sequence[E], S2 loser.Sequence[E]](t *testing.T, a S1, b S2, less func(E, E) bool) {
	t.Helper()
	count := 0
	for a.Next() {
		count++
		if !b.Next() {
			t.Fatalf("b ended before a after %d elements", count)
		}
		if less(a.At(), b.At()) || less(b.At(), a.At()) {
			t.Fatalf("position %d: %v != %v", count, a.At(), b.At())
		}
	}
	if b.Next() {
		t.Fatalf("a ended before b after %d elements", count)
	}
}

func TestMerge(t *testing.T) {
	tests := []struct {
		name string
		args []*List
		want *List
	}{
		{
			name: "empty input",
			want: NewList(),
		},
		{
			name: "one list",
			args: []*List{NewList(1, 2, 3, 4)},
			want: NewList(1, 2, 3, 4),
		},
		{
			name: "two lists",
			args: []*List{NewList(3, 4, 5), NewList(1, 2)},
			want: NewList(1, 2, 3, 4, 5),
		},
		{
			name: "two lists, first empty",
			args: []*List{NewList(), NewList(1, 2)},
			want: NewList(1, 2),
		},
		{
			name: "two lists, second empty",
			args: []*List{NewList(1, 2), NewList()},
			want: NewList(1, 2),
		},
		{
			name: "two lists b",
			args: []*List{NewList(1, 2), NewList(3, 4, 5)},
			want: NewList(1, 2, 3, 4, 5),
		},
		{
			name: "two lists c",
			args: []*List{NewList(1, 3), NewList(2, 4, 5)},
			want: NewList(1, 2, 3, 4, 5),
		},
		{
			name: "three lists",
			args: []*List{NewList(1, 3), NewList(2, 4), NewList(5)},
			want: NewList(1, 2, 3, 4, 5),
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			less := func(a, b uint64) bool { return a < b }
			lt := loser.New[uint64](tt.args, math.MaxUint64)
			checkIterablesEqual(t, tt.want, lt, less)
		})
	}
}
