extends Node

@export var rotated: Node3D
@export var proximity_radius: float
@export var modification_curve: Curve
var start_rotation
var reciever: InteractionReciever

func _ready() -> void:
	print(self.get_path(), rotated)
	print_stack()
	start_rotation =  rotated.quaternion

func _on_interaction_area_interaction_reciever_entered(rec: InteractionReciever) -> void:
	if reciever == null:
		reciever = rec


func _on_interaction_area_interaction_reciever_exited(rec: InteractionReciever) -> void:
	if reciever == rec:
		reciever = null
		rotated.quaternion = start_rotation

func _process(_delta: float) -> void:
	if reciever == null:
		rotated.quaternion = start_rotation
		return
	
	var camera: Camera3D = get_viewport().get_camera_3d()
	var rotation_direction : float = -sign(camera.basis.x.dot(reciever.global_position - rotated.global_position))
	var result_quaternion: Quaternion = Quaternion(-camera.basis.z,PI + 1.5707963267948966 * rotation_direction)
	var distance_without_y: float = Vector2(rotated.global_position.x,rotated.global_position.z).distance_to(Vector2(reciever.global_position.x,reciever.global_position.z))
	var calculated_angle: Quaternion = start_rotation.slerp(result_quaternion,modification_curve.sample(clamp(proximity_radius/distance_without_y,0,1)))
	rotated.quaternion = calculated_angle
