package main

import (
	"flag"
	"log"
	"math"
	"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)
	}

	step := 32
	win.WhileKeyDown(ebiten.KeyLeft, env.changeOrigin(-step, +0))
	win.WhileKeyDown(ebiten.KeyRight, env.changeOrigin(+step, +0))
	win.WhileKeyDown(ebiten.KeyUp, env.changeOrigin(+0, -step))
	win.WhileKeyDown(ebiten.KeyDown, env.changeOrigin(+0, +step))

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

	win.OnMouseClick(env.showCellData)
	win.OnMouseWheel(env.changeZoom)

	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) changeZoom(_, byY float64) {
	e.scenario.Zoom *= math.Pow(1.2, byY)
}

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

func (e *env) showCellData() {
	screenX, screenY := ebiten.CursorPosition()
	viewX, viewY := e.scenario.Viewpoint.X+screenX, e.scenario.Viewpoint.Y+screenY

	log.Printf("Click registered at (%d,%d) screen, (%d,%d) virtual", screenX, screenY, viewX, viewY)

	cell, pos := e.scenario.CellAtCursor()
	log.Printf("Viewpoint: %#+v z=%v", e.scenario.Viewpoint, e.scenario.ZIdx)
	log.Printf("Cell under cursor: (%.2f,%.2f,%d): %#+v", pos.X, pos.Y, pos.Z, cell)
}
