extends Position2D
tool
export var node:PackedScene = null

func _ready() -> void:
	if not Engine.editor_hint: 
		GameState.connect("player_just_died", self,"_on_Player_died")
	_spawn()
	


func _exit_tree() -> void:
	if not Engine.editor_hint: 
		despawn()
		


func _on_VisibilityNotifier2D_screen_entered() -> void:
	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():
	print("SPAWN - PLAYER DIED")
	$RespawnTimer.start()
	

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



func _on_RespawnTimer_timeout() -> void:
	despawn()
	if $VisibilityNotifier2D.is_on_screen():
		respawn()
