package main

import (
	"fmt"

	"tetris/assets"
	"tetris/engine/audio"
	"tetris/engine/core"
	"tetris/engine/graphics"
	"tetris/engine/render"
	"tetris/game"
	"tetris/game/state/handlers"
	"tetris/game/state/machine"

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

func main() {
	if err := game.LoadConfig("./config.json"); err != nil {
		fmt.Println("Failed to load config:", err)
	}

	render.Init(render.Config{
		Title:        "Tetris",
		WindowWidth:  685,
		WindowHeight: 600,
		RenderWidth:  685,
		RenderHeight: 600,
		ScaleFlags:   render.SCALE_INTEGER,
	})
	defer render.Exit()

	// Dont close application when user presses escape
	rl.SetExitKey(rl.KeyNull)

	// Set window icon
	if icon := graphics.LoadImageFromMemory(".png", assets.Icon); icon != nil {
		rl.SetWindowIcon(*icon)
		rl.UnloadImage(icon)
	}

	audio.Init()
	defer audio.Exit()

	// Set volume from config
	audio.SetVolume(core.ByteToClampedFloat32(game.Config.SoundVolume))
	audio.LoadLibrary(assets.LoadSound())

	// Load texture
	texture := graphics.LoadTextureFromMemory(".png", assets.Sprite)
	defer rl.UnloadTexture(texture)
	render.SetTexture(texture)
	render.SetFont(&assets.Font)

	// Setup state machine.
	fsm := machine.New()
	fsm.Register("menu", handlers.NewMainMenu(fsm))
	fsm.Register("options", handlers.NewOptionsMenu())
	fsm.Register("gameover", &handlers.GameOver{})
	fsm.Register("gameplay", handlers.NewGamePlay())
	fsm.Start("menu")

	// Enter game loop
	for !rl.WindowShouldClose() {
		audio.Update()
		if !fsm.Update(rl.GetFrameTime()) {
			break
		}
		fsm.Render()
	}
}
