package api

import (
	"net/http/httptest"
	"testing"
)

func TestGenreTotalPrefersEmbysOwnCount(t *testing.T) {
	if got := genreTotal(412, 48, 48, 48); got != 412 {
		t.Fatalf("genreTotal = %d, want the reported 412", got)
	}
}

func TestGenreTotalKeepsScrollingWhenNobodyCounted(t *testing.T) {
	// A full page with no count: there may be more, so the total has to sit past what has
	// been delivered or the television stops half way through the genre.
	if got := genreTotal(0, 48, 48, 48); got <= 96 {
		t.Fatalf("genreTotal = %d, want more than the 96 delivered", got)
	}
}

func TestGenreTotalStopsOnAShortPage(t *testing.T) {
	// A short page is the end of the genre. Claiming anything beyond it leaves the grid
	// asking for a page that will never come.
	if got := genreTotal(0, 48, 11, 48); got != 59 {
		t.Fatalf("genreTotal = %d, want exactly the 59 delivered", got)
	}
	if got := genreTotal(0, 0, 0, 48); got != 0 {
		t.Fatalf("genreTotal = %d, want 0 for a genre with nothing in it", got)
	}
}

func TestQueryOffsetTreatsZeroAsAValueRatherThanAMissingOne(t *testing.T) {
	cases := map[string]int{
		"":                0,
		"offset=0":        0,
		"offset=48":       48,
		"offset=-3":       0,
		"offset=nonsense": 0,
	}
	for query, want := range cases {
		r := httptest.NewRequest("GET", "/v1/genres/Comedy/items?"+query, nil)
		if got := queryOffset(r, "offset"); got != want {
			t.Errorf("queryOffset(%q) = %d, want %d", query, got, want)
		}
	}
}

func TestGenreItemTypeSeparatesMoviesAndSeries(t *testing.T) {
	cases := map[string]string{
		"":         "Movie,Series",
		"movie":    "Movie",
		"Movie":    "Movie",
		"series":   "Series",
		" Series ": "Series",
	}
	for input, want := range cases {
		got, ok := genreItemType(input)
		if !ok || got != want {
			t.Errorf("genreItemType(%q) = %q, %v; want %q, true", input, got, ok, want)
		}
	}
	if got, ok := genreItemType("Episode"); ok || got != "" {
		t.Fatalf("genreItemType(Episode) = %q, %v; want empty, false", got, ok)
	}
}
