package main

import (
	"flag"
	"image"
	"log"
	"math"
	"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")
	setName  = flag.String("set", "", "Name of a set, e.g., map01")

	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 {
	set       *assetstore.Set
	step      int
	state     state
	lastState state
}

type state struct {
	objIdx    int
	spriteIdx int

	zoom   float64
	origin image.Point
}

func main() {
	flag.Parse()

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

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

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

	state := state{zoom: 8.0}
	env := &env{
		set:       set,
		state:     state,
		lastState: state,
	}

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

	win.OnKeyUp(ebiten.KeyLeft, env.changeObjIdx(-1))
	win.OnKeyUp(ebiten.KeyRight, env.changeObjIdx(+1))

	win.OnKeyUp(ebiten.KeyUp, env.changeSpriteIdx(+1))
	win.OnKeyUp(ebiten.KeyDown, env.changeSpriteIdx(-1))

	win.OnMouseWheel(env.changeZoom)

	// Main thread now belongs to ebiten
	if err := win.Run(); err != nil {
		log.Fatal(err)
	}
}

func (e *env) Update(screenX, screenY int) error {
	curObj, err := e.curObject()
	if err != nil {
		return err
	}

	if e.step == 0 || e.lastState != e.state {
		log.Printf(
			"new state: object=%d/%d (%s) numFrames=%d sprite=%d zoom=%.2f",
			e.state.objIdx,
			e.set.NumObjects,
			curObj.Name,
			curObj.NumSprites,
			e.state.spriteIdx,
			e.state.zoom,
		)
	}

	e.step += 1
	e.lastState = e.state

	return nil
}

func (e *env) Draw(screen *ebiten.Image) error {
	sprite, err := e.curSprite()
	if err != nil {
		return err
	}

	cam := ebiten.GeoM{}
	cam.Scale(e.state.zoom, e.state.zoom) // apply current zoom factor

	// TODO: centre the image

	return screen.DrawImage(sprite.Image, &ebiten.DrawImageOptions{GeoM: cam})
}

func (e *env) changeObjIdx(by int) func() {
	return func() {
		old := e.state.objIdx
		e.state.objIdx += by

		if e.state.objIdx < 0 {
			e.state.objIdx = 0
		}

		if e.state.objIdx > e.set.NumObjects-1 {
			e.state.objIdx = e.set.NumObjects - 1
		}

		// reset sprite index when object changes
		if old != e.state.objIdx {
			e.state.spriteIdx = 0
		}
	}
}

func (e *env) changeSpriteIdx(by int) func() {
	return func() {
		obj, err := e.curObject()
		if err != nil {
			log.Printf("Encountered %v trying to change sprite index", err)
			return
		}

		e.state.spriteIdx += by
		if e.state.spriteIdx < 0 {
			e.state.spriteIdx = 0
		}

		if e.state.spriteIdx > obj.NumSprites-1 {
			e.state.spriteIdx = obj.NumSprites - 1
		}
	}
}

func (e *env) changeZoom(_, y float64) {
	// Zoom in and out with the mouse wheel
	e.state.zoom *= math.Pow(1.2, y)
}

func (e *env) curObject() (*assetstore.Object, error) {
	return e.set.Object(e.state.objIdx)
}

func (e *env) curSprite() (*assetstore.Sprite, error) {
	obj, err := e.curObject()
	if err != nil {
		return nil, err
	}

	return obj.Sprite(e.state.spriteIdx)
}
