extends Node2D

# Is given in blocks
export var movement_radius = 6

var Rope = preload("res://src/Contraptions/Rope/Rope.tscn")
var RopeAnchor = preload("res://src/Contraptions/Rope/RopeAnchor.tscn")
var rope
var is_first_signal = true

func _on_LevelTemplate_ready() -> void:
	rope = Rope.instance()
	# For some reason the rope only can be instanced in the parent scene 
	# The scene also has to be ready beforehand
	get_parent().add_child(rope)
	rope.rope_end = get_node("RopeAnchor")
	rope.rope_start = get_node("WhatAreFrog")
	rope.rope_end_joint = get_node("RopeAnchor/cshape/pjoint")
	rope.rope_start_joint = get_node("WhatAreFrog/cshape/pjoint")
	rope.spawn_rope($WhatAreFrog.global_position, $RopeAnchor.global_position, movement_radius, false)

	$WhatAreFrog.bind_to_anchor($RopeAnchor, movement_radius)

# Executes on frog death
# The old switchero
func _on_WhatAreFrog_child_exiting_tree(_node:Node) -> void:
	if(is_first_signal):
		var anchor = RopeAnchor.instance()
		anchor.mode = 0
		add_child(anchor)
		anchor.global_position = rope.rope_start_joint.global_position
		rope.queue_free()
		rope = Rope.instance()
		# For some reason the rope only can be instanced in the parent scene 
		# The scene also has to be ready beforehand
		get_parent().add_child(rope)
		rope.rope_end = $RopeAnchor
		rope.rope_start = anchor
		rope.rope_end_joint = $RopeAnchor/cshape/pjoint
		rope.rope_start_joint = anchor.get_node("cshape/pjoint")
		rope.spawn_rope(anchor.global_position, $RopeAnchor.global_position, movement_radius, false)
		is_first_signal = false
			# rope.rope_start = anchor
			# anchor.global_position = rope.rope_start_joint.global_position
			# rope.rope_start_joint = anchor.get_node("cshape/pjoint")
			# rope.rope_pieces[0] = anchor
			# var first_piece = rope.rope_pieces[1]
			# rope.rope_start_joint.node_a = anchor.get_path
			# rope.rope_start_joint.node_b = first_piece.get_path()
			# first_piece.get_node("cshape/pjoint").node_b = anchor.get_path()
	else:
		pass
	# var lastPiecePath: NodePath = $WhatAreFrog/cshape/pjoint.node_b
	# print(lastPiecePath)
	# var lastPiece: Node = get_node(lastPiecePath)
	# print(lastPiece)
	# lastPiece.get_node("cshape/pjoint").node_a = anchor.get_path()
