package icecast

import "testing"

func TestMapStreamTitleToRadioTextSanitizeAndTruncate(t *testing.T) {
	got := mapStreamTitleToRadioText("  Artist\t-\nSong \u2603  ", RadioTextOptions{
		Enabled: true,
		Prefix:  "Now: ",
		MaxLen:  13,
	})
	if got != "Now: Artist -" {
		t.Fatalf("mapped=%q want %q", got, "Now: Artist -")
	}
}

func TestMapStreamTitleToRadioTextDisabledReturnsEmpty(t *testing.T) {
	got := mapStreamTitleToRadioText("Artist - Song", RadioTextOptions{Enabled: false})
	if got != "" {
		t.Fatalf("mapped=%q want empty", got)
	}
}

func TestRadioTextRelayOnlyOnChange(t *testing.T) {
	calls := 0
	last := ""
	relay := NewRadioTextRelay(RadioTextOptions{
		Enabled:      true,
		OnlyOnChange: true,
	}, "", func(rt string) error {
		calls++
		last = rt
		return nil
	})

	if err := relay.HandleStreamTitle("Artist - Song"); err != nil {
		t.Fatalf("first handle: %v", err)
	}
	if err := relay.HandleStreamTitle("Artist - Song"); err != nil {
		t.Fatalf("second handle: %v", err)
	}
	if calls != 1 {
		t.Fatalf("calls=%d want 1", calls)
	}
	if last != "Artist - Song" {
		t.Fatalf("last=%q want %q", last, "Artist - Song")
	}
}

func TestRadioTextRelayInitialSuppressesSameUpdate(t *testing.T) {
	calls := 0
	relay := NewRadioTextRelay(RadioTextOptions{
		Enabled:      true,
		OnlyOnChange: true,
	}, "Station default", func(string) error {
		calls++
		return nil
	})

	if err := relay.HandleStreamTitle("Station default"); err != nil {
		t.Fatalf("handle: %v", err)
	}
	if calls != 0 {
		t.Fatalf("calls=%d want 0", calls)
	}
}
