extends Node

@export var lobby_menu : LobbyMenu
var menu_showing : bool = false;

@export var server : Server

@export var level: Level

@onready var chat : ChatMenu = $ChatMenu

func _ready() -> void:
	lobby_menu.enet_host_toggled_on.connect(_enet_host_on)
	lobby_menu.enet_join_pressed.connect(_enet_join_pressed)
	lobby_menu.disconnect_button_pressed.connect(_disconnect_button_pressed)
	lobby_menu.enet_host_toggled_off.connect(_menu_toggle_host_off)
	server.client_connected_to_server.connect(_client_joined_server)
	server.remove_client_from_server.connect(_remove_client_from_server)
	server.client_disconnected_from_server.connect(_disconnect_from_server)
	server.server_close.connect(_server_close)
	server.game_log.connect(_server_send_chat_message)

func _physics_process(_delta: float) -> void:    
	pause_toggle()


func pause_toggle():
	if Input.is_action_just_pressed("pause"):
		if Global.inventory_showing:
			var player_id : int = multiplayer.get_unique_id()
			var player : Player = level.get_node("Player"+str(player_id))
			player.handle_open_inventory(true)
			return
		if !menu_showing:
			lobby_menu.show()
			menu_showing = true
			Global.in_menu = true
			Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
			
		elif menu_showing:
			lobby_menu.hide()
			menu_showing = false
			Global.in_menu = false
			Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

func _enet_host_on(username: String) -> void:
	print("Server started, Host: " + username);
	server.enet_create_host()


func _enet_join_pressed(_username: String) -> void:
	print("... Joining " + Global.enet_address)
	var playername : Player = level.get_node("Player1")
	level.remove_child(playername)
	server.enet_create_client(Global.enet_address)


func _client_joined_server() -> void:

	var player_id : int = multiplayer.get_unique_id()
	level.request_spawn_player.rpc(player_id)
	lobby_menu.hide()
	menu_showing = false
	Global.in_menu = false

func _menu_toggle_host_off() -> void:
	server.destroy_lobby()
	lobby_menu.reset_visible()

func _server_close() -> void:
	level.remove_players(false)
	lobby_menu.reset_visible()

func _disconnect_button_pressed():
	server.disconnect_client()
	lobby_menu.reset_visible()

func _remove_client_from_server(id : int) -> void:
	level.remove_client_from_server.rpc_id(1, id)

func _disconnect_from_server():
	level.disconnect_from_server()


func _server_send_chat_message(message : String, color : Color) -> void:
	chat.send_message(message, false, color)
