package input_test

import (
	"context"
	"mayhem-party/src/device/input"
	"os"
	"path"
	"testing"
)

func TestNew(t *testing.T) {
	r := input.New(context.Background())
	for i := 0; i < 15; i++ {
		batch := r.Read()
		for _, got := range batch {
			t.Logf("[%d] %c:%v", i, got.Char, got.Down)
		}
	}
}

func TestNewRemapped(t *testing.T) {
	d := t.TempDir()
	remap := path.Join(d, "remap")
	if err := os.WriteFile(remap, []byte(`{"a":"b"}`), os.ModePerm); err != nil {
		t.Fatal(err)
	}

	rand := path.Join(d, "rand")
	if err := os.WriteFile(rand, []byte(`{"a":1}`), os.ModePerm); err != nil {
		t.Fatal(err)
	}

	os.Setenv("INPUT_REMAP_FILE", remap)
	os.Setenv("INPUT_RANDOM_WEIGHT_FILE", rand)
	t.Cleanup(func() {
		os.Unsetenv("INPUT_REMAP_FILE")
		os.Unsetenv("INPUT_RANDOM_WEIGHT_FILE")
	})

	r := input.New(context.Background())
	for i := 0; i < 15; i++ {
		batch := r.Read()
		for j := range batch {
			if batch[j].Char != 'b' {
				t.Errorf("%c", batch[j].Char)
			}
			t.Logf("[%d][%d] %c|%v", i, j, batch[j].Char, batch[j].Down)
		}
	}
}

func TestNewBuffered(t *testing.T) {
	os.Setenv("INPUT_BUFFERED", "true")
	t.Cleanup(func() {
		os.Unsetenv("INPUT_BUFFERED")
	})

	r := input.New(context.Background())
	for i := 0; i < 15; i++ {
		batch := r.Read()
		for j := range batch {
			t.Logf("[%d][%d] %c|%v", i, j, batch[j].Char, batch[j].Down)
		}
	}
}

func TestNewRandomWeightFile(t *testing.T) {
	d := t.TempDir()
	p := path.Join(d, "f")
	if err := os.WriteFile(p, []byte(`{"a":1}`), os.ModePerm); err != nil {
		t.Fatal(err)
	}

	os.Setenv("INPUT_RANDOM_WEIGHT_FILE", p)
	t.Cleanup(func() {
		os.Unsetenv("INPUT_RANDOM_WEIGHT_FILE")
	})

	r := input.New(context.Background())
	for i := 0; i < 15; i++ {
		batch := r.Read()
		for _, got := range batch {
			if got.Char != 'a' {
				t.Error(got)
			}
		}
	}
}
