extends Control

@onready var _ip_input: LineEdit = $Panel/VBox/IPInput
@onready var _port_input: LineEdit = $Panel/VBox/PortInput
@onready var _status_label: Label = $Panel/VBox/StatusLabel
@onready var _connect_btn: Button = $Panel/VBox/ConnectBtn
@onready var _back_btn: Button = $Panel/VBox/BackBtn


func _ready() -> void:
	_ip_input.text = "127.0.0.1"
	_port_input.text = str(NetworkManager.DEFAULT_PORT)
	_status_label.text = ""

	NetworkManager.connection_succeeded.connect(_on_connected)
	NetworkManager.connection_failed.connect(_on_failed)

	_connect_btn.pressed.connect(_on_connect_pressed)
	_back_btn.pressed.connect(_on_back_pressed)


func _on_connect_pressed() -> void:
	var address: String = _ip_input.text.strip_edges()
	var port: int = int(_port_input.text.strip_edges())
	if address.length() == 0:
		_status_label.text = "Adresse invalide"
		return
	_status_label.text = "Connexion en cours..."
	_connect_btn.disabled = true
	NetworkManager.join_server(address, port)


func _on_connected() -> void:
	_status_label.text = "Connecte!"
	get_tree().change_scene_to_file("res://scenes/Main.tscn")


func _on_failed() -> void:
	_status_label.text = "Connexion echouee"
	_connect_btn.disabled = false


func _on_back_pressed() -> void:
	get_tree().change_scene_to_file("res://scenes/MainMenu.tscn")
