extends RichTextLabel

@export var login: Login
@export var api_config: ApiConfig
var api := ServerApi.new(api_config)

# docs.redotengine.org/en/stable/tutorials/networking/websocket.html
var time_channel = WebSocketPeer.new()


func _ready() -> void:
	login.connect("login_successful", on_login)
	(
		ConnectionChannel
		. connect(
			"on_channel_token_received",
			on_channel_token_received,
		)
	)


func on_login(session: PlayerLoginSession):
	ConnectionChannel.connect_to_channel(session.token)
	ConnectionChannel.request_channel_token(Message.Channels.TIME)


func on_channel_token_received(msg: ProvidedConnectionTokenMessage) -> void:
	if time_channel.get_ready_state() != WebSocketPeer.STATE_CLOSED:
		return
	if msg.channel != Message.Channels.TIME:
		return
	time_channel.handshake_headers = PackedStringArray(
		["Authorization: " + msg.token],
	)
	time_channel.connect_to_url("ws://localhost:8080/ws/time")


func _process(_delta: float) -> void:
	time_channel.poll()
	var state = time_channel.get_ready_state()

	if state != WebSocketPeer.STATE_OPEN:
		return
	while time_channel.get_available_packet_count():
		var msg: CurrentUnixTimeMessage = Message.deserialize(
			time_channel.get_packet().get_string_from_utf8(), [CurrentUnixTimeMessage]
		)
		if msg == null:
			continue
		self.text = str(msg.time)