package assetstore

import (
	"errors"
	"log"

	"code.ur.gs/lupine/ordoor/internal/sets"
)

var (
	ErrOutOfBounds = errors.New("Out of bounds")
)

type Set struct {
	assets *AssetStore

	raw        *sets.MapSet
	NumObjects int
}

func (s *Set) Object(idx int) (*Object, error) {
	if idx < 0 || idx >= s.NumObjects {
		return nil, ErrOutOfBounds
	}

	return s.assets.Object(s.raw.Palette[idx])
}

func (a *AssetStore) Set(name string) (*Set, error) {
	name = canonical(name)

	if set, ok := a.sets[name]; ok {
		return set, nil
	}
	log.Printf("Loading set %v", name)

	filename, err := a.lookup(name, "set", "Sets")
	if err != nil {
		return nil, err
	}

	raw, err := sets.LoadSet(filename)
	if err != nil {
		return nil, err
	}

	set := &Set{
		assets:     a,
		raw:        raw,
		NumObjects: len(raw.Palette),
	}
	a.sets[name] = set

	return set, nil
}
