package handlers

import (
	"image/color"

	"tetris/assets"
	"tetris/engine/audio"
	"tetris/engine/core"
	"tetris/engine/render"
	"tetris/game/state"

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

type GameOver struct {
	blinkTimer core.IntervalTimer
	textColor  color.RGBA
}

func (GameOver *GameOver) Enter() {
	audio.Play(assets.SFX_GAME_OVER)
	GameOver.blinkTimer = core.NewIntervalTimer(0.2)
	GameOver.textColor = rl.White
}

func (GameOver) Exit() {
}

func (GameOver) soundDone() bool {
	return !audio.IsPlaying(assets.SFX_GAME_OVER)
}

func (GameOver *GameOver) Update(fsm state.Transitioner, delta float32) {
	if GameOver.blinkTimer.UpdateReset(delta) {
		if GameOver.textColor == rl.Red {
			GameOver.textColor = rl.White
		} else {
			GameOver.textColor = rl.Red
		}
	}

	if GameOver.soundDone() {
		if rl.IsKeyPressed(rl.KeyEnter) {
			fsm.Switch("gameplay")
		} else if rl.IsKeyPressed(rl.KeyQ) {
			fsm.Switch("menu")
		}
	}
}

func (GameOver GameOver) Render() {
	render.Begin(rl.Black)
	render.DrawTextCenter(340, 200, 32, "Game Over", GameOver.textColor)
	if GameOver.soundDone() {
		render.DrawTextCenter(340, 290, 16, "Press ENTER to restart", rl.White)
		render.DrawTextCenter(340, 316, 16, "Press Q to return to menu", rl.White)
	}
	render.End()
}
