extends Area2D


export (float, 0.0, 1000.0) var automatic_camera = 0
export (float, 0.1, 2.0) var fade_speed = 0.1

export var limit_left = false
export var limit_right = false

export var only_camera = false

var camera

# Declare member variables here. Examples:
# var a = 2
# var b = "text"


# Called when the node enters the scene tree for the first time.
func _ready():
	connect("body_enter", self, "on_body_enter")
	if get_tree().get_nodes_in_group("Camera"):
		camera = get_tree().get_nodes_in_group("Camera")[0]

func _process(delta):
	
	if not camera:
		if get_tree().get_nodes_in_group("Camera"):
			camera = get_tree().get_nodes_in_group("Camera")[0]
		else: return

	var bodies = get_overlapping_bodies()
	for body in bodies:
		if body.is_in_group("Player") and not only_camera:
			set_automatic_camera()
			return
			
	if not only_camera: return
	if not camera: return
	
	if position.x < camera.position.x:
		set_automatic_camera()


func set_automatic_camera():
	Utils.interpolate(camera, "automatic_camera_movement", camera.automatic_camera_movement, automatic_camera, fade_speed)
	Utils.execute_after(self, "limit_camera_boundaries", fade_speed)


func limit_camera_boundaries():
	
	if limit_left: 		camera.horizontalBoundary.x = camera.position.x - 640
	if limit_right: 	camera.horizontalBoundary.y = camera.position.x + 640
	
	queue_free()
