extends Camera2D

var lastValid = false
var player = null

var speedMod = 0

func _ready():
	get_tree().get_root().size_changed.connect(resize) 

func resetZoom():
	return Vector2.ONE * 3 * get_viewport().size.length() / 3000

func _process(delta):
	if is_instance_valid(player):
		var velocModifier = clamp(abs(player.velocity.x) - 700, 0, 1000)
		var direction = clamp(player.velocity.x, -1, 1)
	
		speedMod = lerpf(speedMod, velocModifier * direction / 5, delta * 10)
	
		global_position = (get_local_mouse_position() / 2.5) + player.global_position
		global_position.x += speedMod
	else:
		lastValid = false
	if player and not lastValid:
		lastValid = true
		var fader = $CanvasLayer/Fader
		$CanvasLayer.visible = true
		fader.offset = Vector2(0, get_viewport().size.y)
		var tween = create_tween()
		tween.set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_SINE)
		tween.tween_property(fader, "offset", Vector2(0, get_viewport().size.y * 2), 0.5).set_delay(0.15)
		
		global_position = player.global_position
		zoom = resetZoom()
		reset_smoothing()
		
		await tween.finished
		fader.offset = Vector2.ZERO

func resize():
	zoom = resetZoom()

func deathAnim():
	var fader = $CanvasLayer/Fader
	var tween = create_tween()
	tween.set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_CUBIC)
	
	tween.tween_property(fader, "offset", Vector2(0, get_viewport().size.y), 0.3)
	player = null
	return tween
