using Godot;
using System;

public partial class RaycastClickHandler : Node3D
{
	[Export] Camera3D Camera { get; set; }
	[Export] float MaxDistance = 100f;

	public override void _Ready()
	{
		if (Camera == null)
		{
			Camera = GetViewport().GetCamera3D();
		}
	}
	
	public override void _UnhandledInput(InputEvent @event)
	{
		if (@event is InputEventMouseButton mouseEvent && mouseEvent.Pressed && mouseEvent.ButtonIndex == MouseButton.Left)
		{
			HandleClick(mouseEvent.Position);
		}
	}

	private void HandleClick(Vector2 mousePosition)
	{
		var from = Camera.ProjectRayOrigin(mousePosition);
		var to = from + Camera.ProjectRayNormal(mousePosition) * MaxDistance;

		var spaceState = GetWorld3D().DirectSpaceState;

		var result = spaceState.IntersectRay(new PhysicsRayQueryParameters3D
		{
			From = from,
			To = to,
			CollisionMask = 1 << 0,
		});

		if (result.Count > 0)
		{
			if (result["collider"].Obj is InteractableObject interactable)
			{
				//interactable.Interact();
			}
		}
		else {
			GameManager.Instance.EmitClearGUISignal();
		}
	}
}
