package api

import "testing"

// Which tab a page opens on is stored per user as a page->tab map, and every
// tabbed page in the web app is in it. The map is small, but it is the one
// preference whose keys have to line up with three different bars, so the
// validation is worth pinning down: an unknown page or an unknown tab is a stale
// or wrong client, and an empty value is how a client says "no default, open on
// whichever tab leads the bar".

func TestNormalizeDefaultTabs(t *testing.T) {
	got, err := normalizeDefaultTabs(map[string]string{
		"charging": " home ",
		"car":      "reminders",
		"settings": "",
	})
	if err != nil {
		t.Fatalf("normalizeDefaultTabs: %v", err)
	}
	if got["charging"] != "home" {
		t.Errorf("charging = %q, want the trimmed \"home\"", got["charging"])
	}
	if got["car"] != "reminders" {
		t.Errorf("car = %q, want \"reminders\"", got["car"])
	}
	// Cleared rather than stored empty, so "no default" has one representation.
	if _, ok := got["settings"]; ok {
		t.Errorf("settings = %q, want the key dropped", got["settings"])
	}

	if empty, err := normalizeDefaultTabs(nil); err != nil || len(empty) != 0 {
		t.Errorf("normalizeDefaultTabs(nil) = %v, %v; want empty and no error", empty, err)
	}

	if _, err := normalizeDefaultTabs(map[string]string{"garage": "info"}); err == nil {
		t.Error("normalizeDefaultTabs accepted a page that has no tabs, want an error")
	}
	// The tab exists, but on another page: the sets are validated per page.
	if _, err := normalizeDefaultTabs(map[string]string{"charging": "reminders"}); err == nil {
		t.Error("normalizeDefaultTabs accepted a tab from another page, want an error")
	}

	// The tab sets are the contract the web app's src/lib/tabs.js mirrors.
	for page, want := range map[string]int{"charging": 2, "car": 10, "settings": 4} {
		if len(validDefaultTabs[page]) != want {
			t.Errorf("%s has %d tabs, want %d", page, len(validDefaultTabs[page]), want)
		}
	}
	if len(validDefaultTabs) != 3 {
		t.Errorf("validDefaultTabs has %d pages, want the 3 tabbed pages", len(validDefaultTabs))
	}
}
