package assetstore

import (
	"log"

	"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
	objects []*Object   // TODO: place the objects directly into the relevant records
	raw     *menus.Menu // TODO: remove raw

	Name string
}

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

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

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

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

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

	return out, nil
}

func (m *Menu) Sprites(objIdx, start, count int) ([]*Sprite, error) {
	return m.objects[objIdx].Sprites(start, count)
}

func (m *Menu) Sprite(objIdx, idx int) (*Sprite, error) {
	return m.objects[objIdx].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 {
		log.Printf("Failed to load i18n data, skipping internationalisatoin: %s", err)
	} else {
		raw.Internationalize(i18n)
	}

	// FIXME: we should parse the menu into a list of elements like "ListBox",
	// "Dialogue", etc, and present those with objects already selected
	objects, err := a.loadMenuObjects(raw)
	if err != nil {
		return nil, err
	}

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

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

func (a *AssetStore) loadMenuObjects(menu *menus.Menu) ([]*Object, error) {
	out := make([]*Object, len(menu.ObjectFiles))
	for i, name := range menu.ObjectFiles {
		filename, err := a.lookup(name, "", "Menu") // Extension already present
		if err != nil {
			return nil, err
		}

		obj, err := a.ObjectByPath(filename)
		if err != nil {
			return nil, err
		}

		out[i] = obj
	}

	return out, nil
}
