package phraser

import (
	"math/rand"
	"strings"
	"testing"
)

// The embedded file must load, or the daemon speaks from hardFloor and nobody
// finds out until he hears the wrong words.
func TestFallbacksLoad(t *testing.T) {
	fb, err := LoadFallbacks(rand.NewSource(1))
	if err != nil {
		t.Fatalf("LoadFallbacks: %v", err)
	}
	if got := fb.FromSources("два литра"); !strings.Contains(got, "два литра") {
		t.Errorf("FromSources = %q, want the sources in it", got)
	}
	if fb.WorldGap() != hardFloor[fbWorldGap] {
		t.Errorf("WorldGap = %q, want the fixed wording %q", fb.WorldGap(), hardFloor[fbWorldGap])
	}
}

// A broken or missing file must not take her last words away: every accessor
// answers from the literal it replaced.
func TestNilFallbacksAnswerFromTheHardFloor(t *testing.T) {
	var fb *Fallbacks
	if got := fb.Chat(); got != hardFloor[fbChat] {
		t.Errorf("Chat = %q, want %q", got, hardFloor[fbChat])
	}
	if got := fb.Unknown(); got != hardFloor[fbQueryUnknown] {
		t.Errorf("Unknown = %q, want %q", got, hardFloor[fbQueryUnknown])
	}
	if got := fb.FromSources("два литра"); got != "вот что я нашла: два литра" {
		t.Errorf("FromSources = %q", got)
	}
	if got := fb.WorldGap(); got != hardFloor[fbWorldGap] {
		t.Errorf("WorldGap = %q", got)
	}
}

// Hearing the identical words every time a request fails is how a failure stops
// registering as one.
func TestFallbacksDoNotRepeat(t *testing.T) {
	fb, err := LoadFallbacks(rand.NewSource(7))
	if err != nil {
		t.Fatalf("LoadFallbacks: %v", err)
	}
	prev := fb.Chat()
	for i := 0; i < 20; i++ {
		got := fb.Chat()
		if got == prev {
			t.Fatalf("chat repeated %q on turn %d", got, i)
		}
		prev = got
	}
}

// The acknowledgements load, fill his words into the frame, and answer from the
// floor when the file is gone.
func TestAcksLoad(t *testing.T) {
	a, err := LoadAcks(rand.NewSource(1))
	if err != nil {
		t.Fatalf("LoadAcks: %v", err)
	}
	got := a.Say(AckFactValue, map[string]string{"key": "вода", "value": "2л"})
	if !strings.Contains(got, "вода") || !strings.Contains(got, "2л") {
		t.Errorf("Say(%s) = %q, want his key and value in it", AckFactValue, got)
	}
	var nilAcks *Acks
	if got := nilAcks.Say(AckNote, nil); got != ackFloor[AckNote] {
		t.Errorf("nil Acks said %q, want the floor %q", got, ackFloor[AckNote])
	}
}
