extends Area2D
class_name DropsBase

var witch
var player
var is_spawning = true
signal collected
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	body_entered.connect(_on_body_entered)
	witch = get_node("/root/Game/Witch")
	collected.connect(witch._on_collect)
	player = get_node("/root/Game/Player")
	_animate_spawn()
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass

func _get_random_landing_position() -> Vector2:
	var offset_x = randf_range(-20,20)
	var offset_y = randf_range(-20,20)
	offset_x += global_position.x
	offset_y += global_position.y
	return Vector2(offset_x,offset_y)

func _animate_spawn() -> void:
	is_spawning = true
	var jump = create_tween()
	var landing = _get_random_landing_position()
	jump.tween_property(self, "global_position:x", landing.x, 0.2).set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_QUAD)
	jump.parallel()
	jump.tween_property(self, "global_position:y", global_position.y - 20, 0.2).set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_QUAD)
	jump.tween_property(self, "global_position:y", landing.y, 0.2).set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_QUAD)
	await jump.finished
	is_spawning = false
	
func _on_body_entered(body: Node2D) -> void:
	if body == player and not is_spawning:
		collect()
	pass

func collect():
	is_spawning = true
	var position_drop = create_tween()
	var target = witch.global_position
	position_drop.tween_property(self, "global_position:y", global_position.y - 20, 0.2).set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_QUAD)
	position_drop.tween_property(self, "global_position:y", target.y, 0.5).set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_QUAD)
	position_drop.parallel()
	position_drop.tween_property(self, "global_position:x", target.x, 0.5).set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_QUAD)
	await position_drop.finished
	var scale_tween = create_tween()
	collected.emit(self)
	scale_tween.tween_property(self, "scale", Vector2.ZERO,0.2)
