package game

import (
	"fmt"

	"gitea.boner.be/bdnugget/goonscape/types"
	rl "github.com/gen2brain/raylib-go/raylib"
)

func (g *Game) GetTileAtMouse() (types.Tile, bool) {
	if !rl.IsMouseButtonPressed(rl.MouseLeftButton) {
		return types.Tile{}, false
	}
	mouse := rl.GetMousePosition()
	ray := rl.GetMouseRay(mouse, g.Camera)

	for x := 0; x < types.MapWidth; x++ {
		for y := 0; y < types.MapHeight; y++ {
			tile := GetTile(x, y)
			tilePos := rl.NewVector3(float32(x*types.TileSize), tile.Height*types.TileHeight, float32(y*types.TileSize))
			boxMin := rl.Vector3Subtract(tilePos, rl.NewVector3(types.TileSize/2, types.TileHeight/2, types.TileSize/2))
			boxMax := rl.Vector3Add(tilePos, rl.NewVector3(types.TileSize/2, types.TileHeight/2, types.TileSize/2))

			if RayIntersectsBox(ray, boxMin, boxMax) {
				fmt.Printf("Clicked: %d, %d\n", tile.X, tile.Y)
				return tile, true
			}
		}
	}
	return types.Tile{}, false
}
