extends Camera3D

class_name DraggableCamera

const SENSITIVITY = 0.01

var interaction_source: DraggableObject
var plane_position: Vector3
@onready var drag_raycast: RayCast3D = $DragRaycast

func _process(_delta: float) -> void:
	var ray_normal = project_local_ray_normal(get_viewport().get_mouse_position())
	drag_raycast.target_position = ray_normal * 10.0
	if drag_raycast.is_colliding():
		plane_position = drag_raycast.get_collision_point()

func _input(event: InputEvent) -> void:
	if Input.is_action_pressed("drag_camera") and event is InputEventMouseMotion:
		global_position -= Vector3.RIGHT * event.relative.x * SENSITIVITY
		global_position += Vector3.FORWARD * event.relative.y * SENSITIVITY
	
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and not event.pressed and interaction_source != null:
		for draggable in interaction_source.filtered_draggables:
			if draggable == interaction_source:
				continue
			interaction_source.interactible.try_interact(draggable)
			break
		end_interaction_seeking()

func start_interaction_seeking(new_interaction_source: DraggableObject) -> void:
	if new_interaction_source.interactible == null:
		return
	interaction_source = new_interaction_source

func end_interaction_seeking() -> void:
	if interaction_source == null:
		return
	
	interaction_source = null
