extends StaticBody3D

@export var node_res: NodeInteractableBase;
@onready var pivot: Node3D = $Pivot;
@onready var cam: Camera3D;
@onready var mesh_inst: MeshInstance3D = $MeshInstance3D;
@onready var ui = $"NodeUI"

var is_queued: bool = false;
var box: BoxShape3D;

func _ready() -> void:
	cam = get_viewport().get_camera_3d();
	mouse_entered.connect(ui.highlight);
	mouse_exited.connect(ui.minimize);
	ui.set_properties(node_res);

func _process(_delta: float) -> void:
	var g_pos: Vector3 = pivot.global_position;
	ui.set_detection_box_size(calc_bb_offset());
	ui.set_screen_position(g_pos, cam);

## Bounding Box ----------------------------------------------------------------
func calc_bb_offset() -> Vector2:
	var aabb: AABB = transform * mesh_inst.mesh.get_aabb();
	return maxmin(aabb.position, aabb.end, aabb.size);

func maxmin(p1: Vector3, p2: Vector3, s: Vector3) -> Vector2:
	var minn: Vector2 = cam.unproject_position(p1);
	var maxx: Vector2 = minn;
	
	var arr: Array[Vector3] = [p1 + Vector3(s.x, 0, 0), p1 + Vector3(0, s.y, 0), p1 + Vector3(0, 0, s.z),
								p2, p2 - Vector3(s.x, 0, 0), p2 - Vector3(0, s.y, 0), p2 - Vector3(0, 0, s.z)];
	
	for vec in arr:
		var vec2: Vector2 = cam.unproject_position(vec);
		for n in range(2):
			if (minn[n] > vec2[n]):
				minn[n] = vec2[n];
			if (maxx[n] < vec2[n]):
				maxx[n] = vec2[n];
	return maxx - minn;

## Input Handling --------------------------------------------------------------
func _input(event: InputEvent) -> void:
	if (ui.is_highlighted and event.is_action_pressed("interact")):
		if (is_queued):
			dequeue_element();
		else:
			queue_element();

## Database Interface ----------------------------------------------------------
func queue_element() -> void:
	print("Queuing");
	node_res.action();
	is_queued = true;
func dequeue_element() -> void:
	print("DeQueuing");
	is_queued = false;
