package places

import (
	"testing"
)

func TestLoad(t *testing.T) {
	store, err := Load("testdata")
	if err != nil {
		t.Fatal(err)
	}
	for _, tt := range []struct {
		name      string
		get       func() (Place, bool)
		wantTitle string
		ok        bool
	}{
		{"state", func() (Place, bool) { return store.State("va") }, "Virginia", true},
		{"state, upper case", func() (Place, bool) { return store.State("VA") }, "Virginia", true},
		{"state file that doesn't parse", func() (Place, bool) { return store.State("tx") }, "", false},
		{"file not named after a state code", func() (Place, bool) { return store.State("zz") }, "", false},
		{"file name in upper case", func() (Place, bool) { return store.State("ca") }, "", false},
		{"state without a file", func() (Place, bool) { return store.State("ny") }, "", false},
		{"city", func() (Place, bool) { return store.City("VA", "ashburn") }, "Ashburn, Virginia", true},
		{"city by name", func() (Place, bool) { return store.City("va", "Ashburn") }, "Ashburn, Virginia", true},
		{"city keyed by name in the file", func() (Place, bool) { return store.City("va", "falls-church") }, "Falls Church, Virginia", true},
		{"city without text", func() (Place, bool) { return store.City("va", "nowhere") }, "", false},
		{"unknown city", func() (Place, bool) { return store.City("va", "leesburg") }, "", false},
		{"city in a state without a file", func() (Place, bool) { return store.City("ny", "ashburn") }, "", false},
	} {
		place, ok := tt.get()
		if ok != tt.ok || ok && place.Title != tt.wantTitle {
			t.Errorf("%s: %q, %v; want %q, %v", tt.name, place.Title, ok, tt.wantTitle, tt.ok)
		}
	}
	va, _ := store.State("va")
	if len(va.Intro) != 2 || len(va.Sections) != 1 || va.Sections[0].Heading != "History" || va.SourceURL != "https://en.wikipedia.org/wiki/Virginia" {
		t.Errorf("state text: %+v", va)
	}
}

func TestLoad_MissingDir(t *testing.T) {
	store, err := Load("testdata/none")
	if err != nil {
		t.Fatalf("missing dir: %v, want no error", err)
	}
	if _, ok := store.State("va"); ok {
		t.Error("missing dir: want no text")
	}
	var nilStore *Store
	if _, ok := nilStore.City("va", "ashburn"); ok {
		t.Error("nil store: want no text")
	}
}

func TestStateName(t *testing.T) {
	for code, want := range map[string]string{"va": "Virginia", "DC": "District of Columbia", "Ny": "New York", "zz": "", "": ""} {
		if got := StateName(code); got != want {
			t.Errorf("StateName(%q) = %q, want %q", code, got, want)
		}
	}
}
