package assetstore

import (
	"github.com/hajimehoshi/ebiten"

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

type Menu struct {
	assets *AssetStore
	fonts  []*Font     // TODO: place the fonts directly into the relevant records
	obj    *Object     // TODO: handle multiple objects in the menu
	raw    *menus.Menu // TODO: remove raw

	Name string
}

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

// FIXME: don't expose this
func (m *Menu) Font(idx int) *Font {
	return m.fonts[idx]
}

func (m *Menu) Images(start, count int) ([]*ebiten.Image, error) {
	out := make([]*ebiten.Image, count)

	sprites, err := m.Sprites(start, count)
	if err != nil {
		return nil, err
	}

	for i, sprite := range sprites {
		out[i] = sprite.Image
	}

	return out, nil
}

func (m *Menu) Sprites(start, count int) ([]*Sprite, error) {
	out := make([]*Sprite, count)

	for i := start; i < start+count; i++ {
		sprite, err := m.Sprite(i)
		if err != nil {
			return nil, err
		}

		out[i-start] = sprite
	}

	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
	}

	var fonts []*Font
	for _, fontName := range raw.FontNames {
		fnt, err := a.Font(fontName)
		if err != nil {
			return nil, err
		}

		fonts = append(fonts, fnt)
	}

	i18n, err := a.i18n()
	if err != nil {
		return nil, err
	}

	raw.Internationalize(i18n)

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

	menu := &Menu{
		assets: a,
		fonts:  fonts,
		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)
}
