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() {
	local := flag.Bool("local", false, "Use local server instead of remote")
	addr := flag.String("addr", "boner.be:6969", "Server address (hostname:port or hostname)")
	flag.Parse()

	if *local && *addr != "boner.be:6969" {
		log.Fatal("Cannot use both -local and -addr flags")
	}

	if *local {
		network.SetServerAddr("localhost:6969")
	} else if *addr != "" {
		// If only hostname is provided, append default port
		if !strings.Contains(*addr, ":") {
			*addr = *addr + ":6969"
		}
		network.SetServerAddr(*addr)
	}

	rl.InitWindow(1024, 768, "GoonScape")
	defer rl.CloseWindow()
	rl.InitAudioDevice()
	defer rl.CloseAudioDevice()

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

	conn, playerID, err := network.ConnectToServer()
	if err != nil {
		log.Fatalf("Failed to connect to server: %v", err)
	}
	defer conn.Close()

	game.Player.ID = playerID
	modelIndex := int(playerID) % len(game.Models)
	game.Player.Model = game.Models[modelIndex].Model
	game.Player.Texture = game.Models[modelIndex].Texture

	go network.HandleServerCommunication(conn, playerID, game.Player, game.OtherPlayers)

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

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

		game.Update(deltaTime)
		game.Render()
	}
}
