package m9zApi

import (
	"testing"

	"tgk-touch/internal/library/m9z"
)

func TestAutomaticModeDemoStoreReturnsCopies(t *testing.T) {
	store := newAutomaticModeDemoStore()

	start := store.getStartTask(0)
	if len(start.Loops) == 0 {
		t.Fatal("demo start task should include loops")
	}
	start.Loops[0].TurnOn = !start.Loops[0].TurnOn
	start.Loops[0].Pwm = 1

	got := store.getStartTask(0)
	if got.Loops[0].Pwm == 1 {
		t.Fatal("demo start task loop was mutated through returned value")
	}

	middle := store.getMiddleTask(0)
	if len(middle.ControlTaskList) == 0 || len(middle.ControlTaskList[0].Loops) == 0 {
		t.Fatal("demo middle task should include control tasks and loops")
	}
	middle.ControlTaskList[0].Loops[0].Pwm = 1

	gotMiddle := store.getMiddleTask(0)
	if gotMiddle.ControlTaskList[0].Loops[0].Pwm == 1 {
		t.Fatal("demo middle task loop was mutated through returned value")
	}
}

func TestNormalizeAutomaticMode(t *testing.T) {
	if got := normalizeAutomaticMode(2); got != 2 {
		t.Fatalf("normalizeAutomaticMode(2) = %d, want 2", got)
	}
	if got := normalizeAutomaticMode(3); got != 0 {
		t.Fatalf("normalizeAutomaticMode(3) = %d, want 0", got)
	}
}

func TestAutomaticModeDemoStoreBuildsTaskPrograms(t *testing.T) {
	store := newAutomaticModeDemoStore()

	programs := map[string]func(uint8) (*m9z.TaskProgram, error){
		"start":  store.getStartTaskProgram,
		"middle": store.getMiddleTaskProgram,
		"stop":   store.getStopTaskProgram,
	}

	for name, build := range programs {
		t.Run(name, func(t *testing.T) {
			program, err := build(1)
			if err != nil {
				t.Fatalf("build %s demo task program failed: %v", name, err)
			}
			if program == nil {
				t.Fatalf("%s demo task program is nil", name)
			}
			if program.Index != 1 {
				t.Fatalf("%s demo task program index = %d, want 1", name, program.Index)
			}
			if len(program.Instructions) == 0 {
				t.Fatalf("%s demo task program should include instructions", name)
			}
		})
	}
}
