package main

import (
	"flag"
	"log"
	"strings"

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

func main() {
	// Parse command line flags
	local := flag.Bool("local", false, "Connect to local server")
	addr := flag.String("addr", "", "Server address (host or host:port)")
	flag.Parse()

	// Set server address based on flags
	if *local {
		if *addr != "" {
			log.Fatal("Cannot use -local and -addr together")
		}
		network.SetServerAddr("localhost:6969")
	} else if *addr != "" {
		// If port is not specified, append default port
		if !strings.Contains(*addr, ":") {
			*addr += ":6969"
		}
		network.SetServerAddr(*addr)
	}

	rl.InitWindow(1024, 768, "GoonScape")
	rl.SetExitKey(0)
	defer rl.CloseWindow()

	rl.InitAudioDevice()
	defer rl.CloseAudioDevice()

	rl.SetTargetFPS(60)

	game := game.New()
	if err := game.LoadAssets(); err != nil {
		log.Fatalf("Failed to load assets: %v", err)
	}
	defer game.Cleanup()

	rl.PlayMusicStream(game.Music)
	rl.SetMusicVolume(game.Music, 0.5)

	for !rl.WindowShouldClose() {
		deltaTime := rl.GetFrameTime()
		rl.UpdateMusicStream(game.Music)
		game.Update(deltaTime)
		game.Render()
	}

	// Wait for clean shutdown
	<-game.QuitChan
}
