extends CanvasLayer

# Top-right live latency readout: this client's RTT to the server, read
# straight from ENet's own peer statistic (no custom protocol needed, unlike
# menu/server_select.gd's pre-connect probe, which has no ENet connection
# yet to read a statistic from). Meaningless for the server itself (peer id
# 1 is the local server, RTT to itself is always ~0), so it stays hidden
# there.

const MARGIN_X := 16.0
const MARGIN_TOP := 20.0
const WIDTH := 100.0
const HEIGHT := 30.0
const UPDATE_INTERVAL := 0.5

const COLOR_GOOD := Color(0.4, 0.9, 0.5)
const COLOR_OK := Color(0.95, 0.75, 0.3)
const COLOR_BAD := Color(0.9, 0.4, 0.4)

var _label: Label
var _timer: float = 0.0


func _ready() -> void:
	layer = 4
	if NetworkManager.is_server:
		queue_free()
		return
	_build_ui()
	_refresh()


func _build_ui() -> void:
	_label = Label.new()
	_label.anchor_left = 1.0
	_label.anchor_right = 1.0
	_label.anchor_top = 0.0
	_label.anchor_bottom = 0.0
	_label.offset_left = -(MARGIN_X + WIDTH)
	_label.offset_right = -MARGIN_X
	_label.offset_top = MARGIN_TOP
	_label.offset_bottom = MARGIN_TOP + HEIGHT
	_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
	_label.add_theme_font_size_override("font_size", 15)
	add_child(_label)


func _process(delta: float) -> void:
	_timer += delta
	if _timer < UPDATE_INTERVAL:
		return
	_timer = 0.0
	_refresh()


func _refresh() -> void:
	var peer := multiplayer.multiplayer_peer
	if peer == null or not (peer is ENetMultiplayerPeer):
		_label.text = ""
		return

	var enet_peer: ENetPacketPeer = (peer as ENetMultiplayerPeer).get_peer(1)
	if enet_peer == null:
		_label.text = "PING: --"
		_label.add_theme_color_override("font_color", Color(0.5, 0.53, 0.6))
		return

	var rtt := int(enet_peer.get_statistic(ENetPacketPeer.PEER_ROUND_TRIP_TIME))
	_label.text = "PING: %d ms" % rtt
	if rtt <= 80:
		_label.add_theme_color_override("font_color", COLOR_GOOD)
	elif rtt <= 180:
		_label.add_theme_color_override("font_color", COLOR_OK)
	else:
		_label.add_theme_color_override("font_color", COLOR_BAD)
