package grid

import (
	"image/color"

	"tetris/engine/graphics"
	"tetris/engine/render"

	rl "github.com/gen2brain/raylib-go/raylib"
)

const (
	// How many pixels wide and tall each cell is.
	CELL_SIZE = 32

	// Number of pixels between each cell
	CELL_SPACING = 1
)

type Grid interface {
	Width() int32
	Height() int32
	Tile(x, y byte) graphics.Tile
}

func DrawBackground(pos rl.Vector2, grid Grid, col color.RGBA, border_size int32, border_col color.RGBA) {
	render.DrawRectBorder(rl.RectangleInt32{
		X:      int32(pos.X),
		Y:      int32(pos.Y),
		Width:  (grid.Width() * (CELL_SIZE + CELL_SPACING)) + CELL_SPACING,
		Height: (grid.Height() * (CELL_SIZE + CELL_SPACING)) + CELL_SPACING,
	}, col, border_size, border_col)
}

func DrawBlock(pos rl.Vector2, x, y byte, tile graphics.Tile) {
	dest := rl.Rectangle{
		X:      float32(int32(pos.X) + (int32(x) * (CELL_SIZE + CELL_SPACING)) + CELL_SPACING),
		Y:      float32(int32(pos.Y) + (int32(y) * (CELL_SIZE + CELL_SPACING)) + CELL_SPACING),
		Width:  float32(CELL_SIZE),
		Height: float32(CELL_SIZE),
	}

	render.DrawTextureRec(tile.GetTexRect(), dest)
}

func Draw(pos rl.Vector2, grid Grid) {
	for y := range byte(grid.Height()) {
		for x := range byte(grid.Width()) {
			DrawBlock(pos, x, y, grid.Tile(x, y))
		}
	}
}
