package main

import (
	"flag"
	"log"
	"os"

	"code.ur.gs/lupine/ordoor/internal/assetstore"
	"code.ur.gs/lupine/ordoor/internal/ui"
	"github.com/hajimehoshi/ebiten"
	"github.com/hajimehoshi/ebiten/audio"
)

var (
	gamePath = flag.String("game-path", "./orig", "Path to a WH40K: Chaos Gate installation")
	menuName = flag.String("menu", "", "Name of a menu, e.g. Main")
)

type env struct {
	ui *ui.Interface

	// fonts    []*assetstore.Font
	// fontObjs []*assetstore.Object

	step      int
	state     state
	lastState state
}

type state struct{}

func main() {
	flag.Parse()

	if *gamePath == "" || *menuName == "" {
		flag.Usage()
		os.Exit(1)
	}

	assets, err := assetstore.New(*gamePath)
	if err != nil {
		log.Fatal(err)
	}

	menu, err := assets.Menu(*menuName)
	if err != nil {
		log.Fatalf("Couldn't load menu %s: %v", *menuName, err)
	}

	/* TODO: move i18n, fonts into assetstore
	if i18n, err := data.LoadI18n(filepath.Join(*gamePath, "Data", data.I18nFile)); err != nil {
		log.Printf("Failed to load i18n data, skipping internationalization: %v", err)
	} else {
		menu.Internationalize(i18n)
	}

	// loadedFonts, err := loadFonts(menu.FontNames...)
	// if err != nil {
	// 	log.Fatalf("Failed to load font: %v", err)
	// }
	*/

	iface, err := ui.NewInterface(menu)
	if err != nil {
		log.Fatalf("Couldn't initialize interface: %v", err)
	}

	if menu.Name == "main" {
		log.Printf("Installing a click handler!")
		widget, err := iface.Widget(2, 5) // Menu 2, submenu 5
		if err != nil {
			log.Fatalf("Couldn't find widget 2,5: %v", err)
		}
		widget.OnMouseClick = func() {
			os.Exit(0)
		}
	}

	// Yay sound
	if _, err := audio.NewContext(48000); err != nil {
		log.Fatalf("Failed to audio: %v", err)
	}
	music, err := assets.Sound("music_interface") // FIXME: should be a reference to Sounds.dat
	if err != nil {
		log.Fatalf("Failed to find interface music: %v", err)
	}
	player, err := music.InfinitePlayer()
	if err != nil {
		log.Fatalf("Failed to generate music player for interface: %v", err)
	}
	player.Play()

	state := state{}
	env := &env{
		ui: iface,
		//objects: menuObjs,
		// fonts:     loadedFonts,
		state:     state,
		lastState: state,
	}

	win, err := ui.NewWindow(env, "View Menu: "+*menuName)
	if err != nil {
		log.Fatal("Couldn't create window: %v", err)
	}

	if err := win.Run(); err != nil {
		log.Fatal(err)
	}
}

func (e *env) Update(screenX, screenY int) error {
	e.step += 1
	e.lastState = e.state

	return e.ui.Update(screenX, screenY)
}

func (e *env) Draw(screen *ebiten.Image) error {
	return e.ui.Draw(screen)
}
