extends Camera3D

class_name PlayerCamera

@export var SENSITIVITY = 0.02


var vertical_compensation : float
var compensation_tween: Tween
var compensate: bool = false
var compensation_speed: float
@export var compensation_time: float = 1.0
@export var compensation_delay: float = 0.5

func _enter_tree() -> void:
	set_multiplayer_authority(get_parent().name.to_int())

func _ready() -> void:
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	# Move to level controller when possible
	#Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	if not is_multiplayer_authority():
		return
	current = true

func _process(delta: float) -> void:
	if compensate:
		if abs(vertical_compensation) <= 0.001:
			vertical_compensation = 0
			compensate = false
			return
		rotate_camera(0,compensation_speed * delta)

func _input(event: InputEvent) -> void:
	if not is_multiplayer_authority():
		return
	if event is InputEventMouseMotion:
		rotate_camera(-event.relative.x * SENSITIVITY,-event.relative.y * SENSITIVITY)

func rotate_camera(x,y) -> void:
	get_parent().rotate_y(x)
	rotation.x = clamp(rotation.x + y,-PI/2,PI/2)
	orthonormalize()
	if sign(vertical_compensation) == sign(y):
		if abs(vertical_compensation) - abs(y) < 0:
			vertical_compensation = 0
		else:
			vertical_compensation -= y

func recoil(x,y) -> void:
	rotate_camera(x,y)
	vertical_compensation -= y
	if compensation_tween:
		compensation_tween.kill()
	compensation_tween = create_tween()
	compensation_tween.tween_interval(compensation_delay)
	compensation_tween.tween_callback(start_compensating)

func start_compensating() -> void:
	compensate = true
	compensation_speed = vertical_compensation / compensation_time
