extends Position2D
tool
export var node:PackedScene = null
onready var player_ref:Player = get_parent().get_node("Player")

func _ready() -> void:
	_spawn()
	


func _exit_tree() -> void:
	if not Engine.editor_hint: 
		player_ref.disconnect("died", self, "_on_Player_died")
		despawn()
		


func _on_VisibilityNotifier2D_screen_entered() -> void:
	if not Engine.editor_hint: 
		player_ref.connect("died", self, "_on_Player_died")
	respawn()

func reset():
	despawn()
	respawn()


func despawn():
	var current_node = get_node("node")
	if current_node != null:
		remove_child(current_node)

func respawn():
	var current_node = get_node("node")
	if current_node == null and node != null:
		_spawn()
	else:
		pass

func _on_Player_died():
	yield(get_tree().create_timer(.7), "timeout")
	despawn()
	if $VisibilityNotifier2D.is_on_screen():
		respawn()

func _spawn():
	var inst = node.instance()
	inst.name = "node"
	add_child(inst)

