extends Spatial

export var target: NodePath
onready var target_node: Spatial = get_node(target)
export var camera_lerp := 1.0

var tracking_cameras = []
onready var prev_camera: Camera = $camera_room_center/camera
onready var current_camera: Camera = $camera_room_center/camera setget set_current_camera

func set_current_camera(new_value: Camera):
	prev_camera = current_camera
	current_camera = new_value
	camera_lerp = 0.0
	$AnimationPlayer.play("switch_camera")

func _on_camera_room_player_entered(player, camera):
	assert(tracking_cameras.find(camera) == -1)
	tracking_cameras.append(camera)
	if tracking_cameras.size() == 1:
		self.current_camera = tracking_cameras.back()

func _on_camera_room_player_exited(player, camera):
	tracking_cameras.erase(camera)
	assert(tracking_cameras.find(camera) == -1)
	if tracking_cameras.size() == 1:
		self.current_camera = tracking_cameras.back()

func _physics_process(delta):
	$main_camera.global_transform.basis = Basis(prev_camera.global_transform.basis.get_rotation_quat().slerp(current_camera.global_transform.basis.get_rotation_quat(), camera_lerp))
	$main_camera.global_transform.origin = lerp(prev_camera.global_transform.origin, current_camera.global_transform.origin, camera_lerp)
