extends Node

var player_manager: PlayerManager = PlayerManager.new()

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	if OS.has_feature("dedicated_server"):
		var chosen_map = "lowpoly_tdm_2.tscn"
		var path_tmpl := "res://scenes/maps/maps/%s"
		var path := path_tmpl % chosen_map
		GameServerManager.current_map = path
		var err := GameServerManager.create_server(player_manager)
		if err != OK:
			push_error("couldn't create a server")
		change_level.call_deferred(path)
		print(get_tree().get_root())
	else:
		var map_dir := DirAccess.open("res://scenes/maps/maps/")
		if map_dir:
			map_dir.list_dir_begin()
			var file_name = map_dir.get_next()
			while file_name != "":
				$UI/CreateServer/Maps.add_item(file_name)
				file_name = map_dir.get_next()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass


func _on_create_server_pressed() -> void:
	$UI/CreateServer.visible = true
	
func _on_join_server_pressed() -> void:
	$UI/JoinServer.visible = true



func _on_create_button_pressed() -> void:
	var chosen_map_index = $UI/CreateServer/Maps.get_selected_items()[0]
	var chosen_map = $UI/CreateServer/Maps.get_item_text(chosen_map_index)
	var path_tmpl := "res://scenes/maps/maps/%s"
	var path := path_tmpl % chosen_map
	GameServerManager.current_map = path
	var err := GameServerManager.create_server(player_manager)
	if err != OK:
		push_error("couldn't create a server")
	$UI.hide()
	change_level.call_deferred(path)

# Call this function deferred and only on the main authority (server).
func change_level(path: String):
	# Remove old level if any.
	var level = $LevelLoader/CurrentLevel
	print("cleaning up the mount node")
	for c in level.get_children():
		level.remove_child(c)
		c.queue_free()
	# Add new level.
	if not ResourceLoader.exists(path):
		print(ERR_DOES_NOT_EXIST)
	var scene: PackedScene = ResourceLoader.load(path)
	if scene.can_instantiate():
		var node: Node3D = scene.instantiate()
		print("loading map: " + node.name)
		level.add_child(node)
	else:
		print("Can't initialize")


func _on_text_edit_text_changed() -> void:
	player_manager.name = $UI/TextEdit.text


func _on_join_button_pressed() -> void:
	$UI.hide()	
	GameServerManager.join_server(player_manager, $UI/JoinServer/IP.text, $UI/JoinServer/Port.text.to_int())
	
