# client_node.gd
class_name ClientNode
extends Node

var udp = PacketPeerUDP.new()
var connected = false

var fast_broadcast_rate = 1.0
var slow_broadcast_rate = 10.0
var current_broadcast_rate = fast_broadcast_rate
var last_broadcast = 0

var ip_address: String = ""

func _ready():
	_try_set_ip()
	udp.set_broadcast_enabled(true)
	udp.set_dest_address("192.168.0.255", 5000)
	SensorSignals.new_sensor_connected.connect(_on_sensor_connected)

func _process(delta):
	if ip_address.length() == 0:
		_try_set_ip()
		return
	last_broadcast += delta
	if last_broadcast >= current_broadcast_rate:
		# Try to contact server
		last_broadcast = 0
		var broadcast_str = ip_address + "|%s" % Time.get_datetime_string_from_system(true)
		print('Broadcasting to UDP: ', broadcast_str)
		udp.put_packet(broadcast_str.to_utf8_buffer())

func _try_set_ip():
	for address in IP.get_local_addresses():
		if address.begins_with("192"):
			if address.ends_with("0.1"):
				continue
			ip_address = address
			break
	
func _on_sensor_connected(sensor_ip, sensor_data):
	current_broadcast_rate = slow_broadcast_rate
