package main

import (
	"flag"
	"log"
	"os"

	"github.com/hajimehoshi/ebiten"

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

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

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

type env struct {
	scenario *scenario.Scenario
}

func main() {
	flag.Parse()

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

	assets, err := assetstore.New(*gamePath)
	if err != nil {
		log.Fatalf("Failed to scan root directory %v: %v", *gamePath, err)
	}

	scenario, err := scenario.NewScenario(assets, *gameMap)
	if err != nil {
		log.Fatalf("Failed to load scenario %v: %v", *gameMap, err)
	}

	env := &env{
		scenario: scenario,
	}

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

	// TODO: click to view cell data

	win.OnKeyUp(ebiten.KeyLeft, env.changeOrigin(-64, +0))
	win.OnKeyUp(ebiten.KeyRight, env.changeOrigin(+64, +0))
	win.OnKeyUp(ebiten.KeyUp, env.changeOrigin(+0, -64))
	win.OnKeyUp(ebiten.KeyDown, env.changeOrigin(+0, +64))

	for i := 0; i <= 6; i++ {
		win.OnKeyUp(ebiten.Key1+ebiten.Key(i), env.setZIdx(i))
	}

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

func (e *env) Update(screenX, screenY int) error {
	return e.scenario.Update(screenX, screenY)
}

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

func (e *env) changeOrigin(byX, byY int) func() {
	return func() {
		e.scenario.Viewpoint.X += byX
		e.scenario.Viewpoint.Y += byY
	}
}

func (e *env) setZIdx(to int) func() {
	return func() {
		e.scenario.ZIdx = to
	}
}
