package gameelement

import (
	"image"
	"math/rand/v2"
	"mover/assets"
	"mover/gamedata"

	"github.com/hajimehoshi/ebiten/v2"
)

type Background struct {
	Sprite      *ebiten.Image
	initialized bool
}

func NewBackground(a gamedata.Area) *Background {
	b := &Background{
		Sprite:      ebiten.NewImage(a.Width, a.Height),
		initialized: false,
	}
	return b
}

func (b *Background) SetInputs(gamedata.GameInputs) {

}

func (b *Background) Update() error {

	if !b.initialized {
		b.Initialize()
	} else {

	}

	return nil
}

func (b *Background) Draw(drawimg *ebiten.Image) {
	//all the stuff before
	op := &ebiten.DrawImageOptions{}
	drawimg.DrawImage(b.Sprite, op)
}

func (b *Background) Initialize() {
	b.ConstructBackground()
	b.initialized = true
}

func (b *Background) ConstructBackground() {
	BLOCK_SIZE := 32

	for i := 0; i < b.Sprite.Bounds().Dx()/BLOCK_SIZE; i++ {
		for j := 0; j < b.Sprite.Bounds().Dy()/BLOCK_SIZE; j++ {

			//select random tile in x and y from tileset
			idx_y := rand.IntN(256 / BLOCK_SIZE)
			idx_x := rand.IntN(256 / BLOCK_SIZE)

			x0 := BLOCK_SIZE * idx_x
			y0 := BLOCK_SIZE * idx_y
			x1 := x0 + BLOCK_SIZE
			y1 := y0 + BLOCK_SIZE

			//translate for grid element we're painting
			op := &ebiten.DrawImageOptions{}
			op.GeoM.Translate(float64(i*BLOCK_SIZE), float64(j*BLOCK_SIZE))
			b.Sprite.DrawImage(assets.ImageBank[assets.TileSet].SubImage(image.Rect(x0, y0, x1, y1)).(*ebiten.Image), op)
		}
	}

	ax := float64(rand.IntN(b.Sprite.Bounds().Dx()/BLOCK_SIZE) * BLOCK_SIZE)
	ay := float64(rand.IntN(b.Sprite.Bounds().Dy()/BLOCK_SIZE) * BLOCK_SIZE)

	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(ax, ay)
	b.Sprite.DrawImage(assets.ImageBank[assets.Altar], op)
}

func (b *Background) RegisterEvents(e gamedata.GameEvent, f func()) {

}
