package catalog

import (
	"reflect"
	"testing"
)

func TestLoadSRD5E2014Catalog(t *testing.T) {
	catalog, err := LoadSRD5E2014()
	if err != nil {
		t.Fatalf("LoadSRD5E2014() error = %v", err)
	}
	if catalog.ID() != SRD5E2014ID || catalog.Ruleset() != SRD5E2014Ruleset {
		t.Fatalf("catalog identity = %q/%q", catalog.ID(), catalog.Ruleset())
	}
	if source := catalog.Source(); source.Version != "5.1" || source.License != "CC-BY-4.0" || source.URL == "" {
		t.Fatalf("catalog source = %#v", source)
	}
	spells := catalog.Spells()
	if len(spells) != 319 {
		t.Fatalf("spell count = %d, want 319", len(spells))
	}
	memberships := 0
	for _, spell := range spells {
		memberships += len(spell.Classes)
	}
	if memberships != 779 {
		t.Fatalf("class memberships = %d, want 779", memberships)
	}

	cureWounds, ok := catalog.Lookup("cure wounds")
	if !ok || cureWounds.Name != "Cure Wounds" || cureWounds.Level != 1 ||
		!reflect.DeepEqual(cureWounds.Classes, []string{"bard", "cleric", "druid", "paladin", "ranger"}) {
		t.Fatalf("Cure Wounds lookup = %#v, present=%t", cureWounds, ok)
	}
	if huntersMark, ok := catalog.Lookup("  HUNTER'S   MARK "); !ok || huntersMark.Name != "Hunter’s Mark" {
		t.Fatalf("Hunter's Mark lookup = %#v, present=%t", huntersMark, ok)
	}
	if _, ok := catalog.Lookup("Definitely Not A Spell"); ok {
		t.Fatal("unknown spell lookup succeeded")
	}
}

func TestCatalogResultsDoNotExposeMutableStorage(t *testing.T) {
	catalog, err := LoadSRD5E2014()
	if err != nil {
		t.Fatal(err)
	}
	spells := catalog.Spells()
	spells[0].Name = "changed"
	spells[0].Classes[0] = "changed"

	acidArrow, ok := catalog.Lookup("Acid Arrow")
	if !ok || acidArrow.Name != "Acid Arrow" || !reflect.DeepEqual(acidArrow.Classes, []string{"wizard"}) {
		t.Fatalf("catalog mutated through Spells(): %#v, present=%t", acidArrow, ok)
	}
	acidArrow.Classes[0] = "changed"
	again, ok := catalog.Lookup("Acid Arrow")
	if !ok || !reflect.DeepEqual(again.Classes, []string{"wizard"}) {
		t.Fatalf("catalog mutated through Lookup(): %#v, present=%t", again, ok)
	}
}
