@tool
class_name EventHandlerWS
extends EventHandler

const BACKEND_URL = "http://89.223.87.146:5004/socket.io"
var _room_id: String = ""
var _jwt_token: String = ""
var _client: SocketIOClient

func _ready():
	initialize_client()
	setup_connections()

func initialize_client():
	_client = SocketIOClient.new(
		BACKEND_URL,
		{"token": _jwt_token, "EIO": "4", "transport": "websocket"}
	)
	add_child(_client)

func setup_connections():
	_client.on_engine_connected.connect(_on_engine_connected)
	_client.on_connect.connect(_on_socket_connect)
	_client.on_disconnect.connect(_on_socket_disconnect)
	_client.on_event.connect(_on_socket_event)

func connect_to_server(jwt: String = ""):
	if !jwt.is_empty():
		_jwt_token = jwt
	_client.update_query_params({"token": _jwt_token})
	_client.socketio_connect()

func _on_engine_connected(_sid: String):
	print("Engine.IO connected")
	_client.socketio_connect()

func _on_socket_connect(_payload, _namespace, error: bool):
	if error:
		error_occurred.emit("Connection failed")
	else:
		print("Socket.IO connected")
		subscribe_to_room(_room_id)

func _on_socket_disconnect(name_space: String):
	print("Disconnected from server")
	disconnected.emit()

	print("Reconnecting...")
	_ready()

func _on_socket_event(event: String, payload: Variant, _namespace):
	print(event, payload)
	match event:
		"reservations_update":
			reservations_updated.emit(payload)
		"error":
			error_occurred.emit(payload.get("message", "Unknown error"))

func subscribe_to_room(room_id: String):
	_room_id = room_id
	_client.socketio_send(
		"subscribe_reservations",
		{"room_id": room_id}
	)

func disconnect_from_server():
	print("Disconnected from server")
	_client.socketio_disconnect()

func _exit_tree():
	disconnect_from_server()
