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")
	fontName = flag.String("font", "", "Name of a font, e.g., basfont12")
	txt      = flag.String("text", "Test string", "Text to render")

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

type state struct {
	zoom   float64
	origin image.Point
}

func main() {
	flag.Parse()

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

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

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

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

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

	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 {
	if e.step == 0 || e.lastState != e.state {
		log.Printf("new state: zoom=%.2f", e.state.zoom)
	}

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

	return nil
}

func (e *env) Draw(screen *ebiten.Image) error {
	xOff := 0
	for _, r := range *txt {
		glyph, err := e.font.Glyph(r)
		if err != nil {
			return err
		}

		op := &ebiten.DrawImageOptions{}
		op.GeoM.Translate(float64(xOff), 0)
		op.GeoM.Scale(e.state.zoom, e.state.zoom) // apply current zoom factor

		if err := screen.DrawImage(glyph.Image, op); err != nil {
			return err
		}

		xOff += glyph.Rect.Dx()
	}

	return nil
}

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