extends Control
class_name MainMenu

const MAP_DIR := "res://scenes/maps/maps/"

@onready var map_list: ItemList = $CreateServerMenu/MapList
@onready var create_server_panel: VBoxContainer = $CreateServerMenu
@onready var join_server_panel: VBoxContainer = $JoinServerMenu

func _get_game_root() -> GameRoot:
	var game_root: GameRoot = find_parent("GameRoot")
	return game_root
	
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	var map_dir := DirAccess.open(MAP_DIR)
	if map_dir:
		map_dir.list_dir_begin()
		var file_name = map_dir.get_next()
		while file_name != "":
			map_list.add_item(file_name)
			file_name = map_dir.get_next()
		GameServerAutoload.current_map = map_list.get_item_text(0)


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


func _on_join_pressed() -> void:
	if create_server_panel.visible:
		create_server_panel.visible = false
	join_server_panel.visible = true


func _on_create_server_pressed() -> void:
	if join_server_panel.visible:
		join_server_panel.visible = false
	create_server_panel.visible = true


func _on_close_join_pressed() -> void:
	join_server_panel.visible = false


func _on_close_create_pressed() -> void:
	create_server_panel.visible = false

func _on_map_list_item_selected(index: int) -> void:
	GameServerAutoload.current_map = map_list.get_item_text(index)


func _on_create_pressed() -> void:
	GameServerAutoload.create_server(false)
	_get_game_root().load_map.emit(GameServerAutoload.current_map)
	visible = false


func _on_join_server_pressed() -> void:
	var ip: String = $JoinServerMenu/Host/TextEdit.text
	var port: int = $JoinServerMenu/Port/TextEdit.text.to_int()
	GameServerAutoload.join_server(ip, port)
	visible = false
	
