package assetstore

import (
	"github.com/hajimehoshi/ebiten"

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

type Menu struct {
	assets *AssetStore
	obj    *Object // TODO: handle multiple objects in the menu
	raw    *menus.Menu

	Name string
}

// FIXME: don't expose this
func (m *Menu) Records() []*menus.Record {
	return m.raw.Records
}

func (m *Menu) Images(start, count int) ([]*ebiten.Image, error) {
	out := make([]*ebiten.Image, count)
	for i := start; i < start+count; i++ {
		sprite, err := m.Sprite(i)
		if err != nil {
			return nil, err
		}

		out[i-start] = sprite.Image
	}

	return out, nil
}

func (m *Menu) Sprite(idx int) (*Sprite, error) {
	return m.obj.Sprite(idx)
}

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

	if menu, ok := a.menus[name]; ok {
		return menu, nil
	}

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

	raw, err := menus.LoadMenu(filename)
	if err != nil {
		return nil, err
	}

	obj, err := a.loadMenuObject(raw) // TODO: multiple objects
	if err != nil {
		return nil, err
	}

	menu := &Menu{
		assets: a,
		obj:    obj,
		raw:    raw,
		Name:   name,
	}

	a.menus[name] = menu
	return menu, nil
}

func (a *AssetStore) loadMenuObject(menu *menus.Menu) (*Object, error) {
	filename := menu.ObjectFiles[0]
	filename, err := a.lookup(filename, "", "Menu") // Extension already present
	if err != nil {
		return nil, err
	}

	return a.ObjectByPath(filename)
}
