extends Node3D

@export var team: Session.TEAMS
@export var spawn_radius: float

func _ready() -> void:
	if not multiplayer.is_server():
		queue_free()
		return
	Session.round_started.connect(spawn)

func _exit_tree() -> void:
	if not multiplayer.is_server():
		return
	Session.round_started.disconnect(spawn)

func spawn():
	if not multiplayer.is_server():
		return
	match team:
		Session.TEAMS.ATTACK:
			for attacker in Lobby.attack_team:
				spawn_player(attacker)
		Session.TEAMS.DEFENCE:
			for defender in Lobby.defence_team:
				spawn_player(defender)
		Session.TEAMS.SPECTATE:
			for specator in Lobby.specators_team:
				spawn_spectator(specator)

func spawn_player(id: int) -> void:
	var player: PackedScene = load("res://scenes/molikman.tscn")
	var inst: Player = player.instantiate()
	Session.player_nodes[id] = inst
	inst.name = str(id)
	if team == Session.TEAMS.DEFENCE:
		Session.defenders_alive += 1 
	elif team == Session.TEAMS.ATTACK:
		Session.attackers_alive += 1 
	
	var distance = randf_range(0,spawn_radius)
	var angle = randf_range(0,TAU)
	var new_position = global_position + Vector3.RIGHT.rotated(Vector3.UP,angle) * distance
	inst.player_id = id
	get_parent().add_child(inst)
	inst.global_position = new_position
	inst.team = team

func spawn_spectator(id: int) -> void:
	var spectator: PackedScene = load("res://scenes/spectator.tscn")
	var inst = spectator.instantiate()
	
	inst.name = str(id)
	var distance = randf_range(0,spawn_radius)
	var angle = randf_range(0,TAU)
	var new_position = global_position + Vector3.RIGHT.rotated(Vector3.UP,angle) * distance
	get_parent().add_child(inst)
	inst.global_position = new_position
	inst.team = team
