extends VBoxContainer
class_name SensorApprovalController

@export var sensor_approval_scene: PackedScene

var sensor_approval_nodes = {}

var window_size: Vector2
var window_center: Vector2

var settings_open: bool = false

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	SettingSignals.settings_opened.connect(_on_settings_opened)
	SettingSignals.settings_closed.connect(_on_settings_closed)
	ServerSignals.sensor_request_received.connect(_on_sensor_request_received)
	ServerSignals.sensor_approved.connect(_on_sensor_approved)
	ServerSignals.sensor_declined.connect(_on_sensor_declined)
	
	window_size = DisplayServer.window_get_size()
	window_center = window_size / 2

func _on_settings_opened():
	settings_open = true
	for val in sensor_approval_nodes:
		remove_child(sensor_approval_nodes[val])

func _on_settings_closed():
	settings_open = false
	for val in sensor_approval_nodes:
		add_child(sensor_approval_nodes[val])
	_update_container_position()

func _on_sensor_request_received(sensor_ip: String, data_provided: Array):
	sensor_approval_nodes[sensor_ip] = sensor_approval_scene.instantiate()
	sensor_approval_nodes[sensor_ip].set_provided_data(sensor_ip, data_provided)
	if not settings_open:
		add_child(sensor_approval_nodes[sensor_ip])
		_update_container_position()

func _update_container_position():
	for val in sensor_approval_nodes:
		var container_size = sensor_approval_nodes[val].size
		container_size = Vector2(container_size.x, container_size.y * sensor_approval_nodes.size())
		position = window_center - (container_size/2)
		return

func _on_sensor_approved(sensor_ip: String):
	_remove_approval_scene(sensor_ip)

func _on_sensor_declined(sensor_ip: String):
	_remove_approval_scene(sensor_ip)

func _remove_approval_scene(sensor_ip: String):
	if sensor_ip not in sensor_approval_nodes:
		return
	remove_child(sensor_approval_nodes[sensor_ip])
	sensor_approval_nodes[sensor_ip].queue_free()
	sensor_approval_nodes.erase(sensor_ip)
	position = window_center - (size/2)
	_update_container_position()
