package main

import (
	"flag"
	"log"
	"os"

	"github.com/hajimehoshi/ebiten"

	"code.ur.gs/lupine/ordoor/internal/assetstore"
	"code.ur.gs/lupine/ordoor/internal/ui"
)

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")

	winX = flag.Int("win-x", 1280, "Pre-scaled window X dimension")
	winY = flag.Int("win-y", 1024, "Pre-scaled window Y dimension")
)

type dlg struct {
	driver *ui.Driver
	list   []string
	pos    int
}

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)
	}

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

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

	// Change the active dialogue
	dialogues := driver.Dialogues()
	if len(dialogues) > 0 {
		dlg := &dlg{
			driver: driver,
			list:   dialogues,
		}
		win.OnKeyUp(ebiten.KeyLeft, dlg.changeDialogue(-1))
		win.OnKeyUp(ebiten.KeyRight, dlg.changeDialogue(+1))
		for i, dialogue := range dlg.list {
			log.Printf("Dialogue %v: %v", i, dialogue)
		}
	}

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

func (d *dlg) changeDialogue(by int) func() {
	return func() {
		newPos := d.pos + by
		if newPos < 0 || newPos > len(d.list)-1 {
			log.Printf("Hiding dialogue %v: %q", d.pos, d.list[d.pos])
			d.driver.HideDialogue()
			return
		}

		locator := d.list[newPos]
		log.Printf("Showing dialogue %v: %q", newPos, locator)

		d.driver.ShowDialogue(locator)
		d.pos = newPos
	}
}
