extends Window

@onready var user_edit: LineEdit = find_child("Username", true, false) as LineEdit
@onready var pass_edit: LineEdit = find_child("Password", true, false) as LineEdit
@onready var info_label: Label = find_child("Info", true, false) as Label

@onready var btn_login: Button = find_child("BtnLogin", true, false) as Button
@onready var btn_register: Button = find_child("BtnRegister", true, false) as Button
@onready var btn_close: Button = find_child("BtnClose", true, false) as Button

@onready var net: Node = get_node_or_null("/root/NetAPI")

func _ready() -> void:
	visible = false

	if btn_login: btn_login.pressed.connect(_do_login)
	if btn_register: btn_register.pressed.connect(_do_register)
	if btn_close: btn_close.pressed.connect(func(): hide())

func open() -> void:
	visible = true
	if info_label: info_label.text = ""
	if pass_edit: pass_edit.text = ""
	if user_edit: user_edit.grab_focus()

func _do_register() -> void:
	if net == null:
		_set_info("NetAPI nav atrasts.")
		return

	var u := user_edit.text.strip_edges()
	var p := pass_edit.text
	if u == "" or p == "":
		_set_info("Ievadi username un password.")
		return

	_set_info("Register...")
	var resp: Dictionary = await net.call("register_user", u, p)
	if resp.get("ok", false) == true:
		_set_info("Registered! Tagad login.")
	else:
		_set_info("Register failed: %s" % str(resp.get("error", resp)))

func _do_login() -> void:
	if net == null:
		_set_info("NetAPI nav atrasts.")
		return

	var u := user_edit.text.strip_edges()
	var p := pass_edit.text
	if u == "" or p == "":
		_set_info("Ievadi username un password.")
		return

	_set_info("Login...")
	var resp: Dictionary = await net.call("login_user", u, p)
	if resp.get("ok", false) == true:
		var uid: int = int(resp.get("user_id", 0))
		var uname: String = str(resp.get("username", u))

		var gm := get_node_or_null("/root/GameManager")
		if gm != null and gm.has_method("set_login"):
			gm.call("set_login", uname, uid)

		_set_info("Logged in: %s" % uname)
		await get_tree().create_timer(0.3).timeout
		hide()
	else:
		_set_info("Login failed: %s" % str(resp.get("error", resp)))

func _set_info(t: String) -> void:
	if info_label:
		info_label.text = t
