# keeps the visual mesh in sync with the attractor radius, and allows the
# attractor radius to be scaled by joystick input of the controller holding the
# object.
extends Node3D

@onready var mesh: MeshInstance3D = $Bounds
@onready var attractor: GPUParticlesAttractorSphere3D = $GPUParticlesAttractorSphere3D

var held_controller: XRController3D = null
const MIN_SCALE = 0.5
const MAX_SCALE = 10
const SCALE_SPEED = 1.0

var initial_rotation: Vector3 = Vector3.ZERO

func _ready() -> void:
	initial_rotation = attractor.global_rotation

func _process(delta: float) -> void:
	# Keep attractor radius in sync with mesh scale
	mesh.scale = Vector3(attractor.radius, attractor.radius, attractor.radius)

	# Keep attractor's global rotation fixed
	attractor.global_rotation = initial_rotation

	# Adjust scale based on controller input if being held
	if held_controller:
		var joystick_y = held_controller.get_vector2("primary").y
		if abs(joystick_y) > 0.1:
			var new_radius = attractor.radius + (joystick_y * SCALE_SPEED * delta)
			attractor.radius = clamp(new_radius, MIN_SCALE, MAX_SCALE)


func _on_pickable_object_picked_up(pickable: XRToolsPickable) -> void:
	held_controller = pickable.get_picked_up_by_controller()

func _on_pickable_object_dropped(_pickable: XRToolsPickable) -> void:
	held_controller = null
