extends Node2D

# Is given in blocks
export var movement_radius = 6
onready var tilemap: TileMap = $"%TileMap"
onready var levelState := get_tree().root.get_child(3).get_node("%LevelState")
onready var signalManager := get_tree().root.get_child(3).get_node("%SignalManager")

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 _ready() -> void:
	signalManager.connect("level_loaded", self, "_on_level_loaded")

func _on_level_loaded() -> 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.tilemap = tilemap
	$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):
		disconnect_rope()
		is_first_signal = false
	else:
		pass

func disconnect_rope() -> void:
		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)


func _on_FrogFreeButton_pushed() -> void:
	$WhatAreFrog.levelState.frees += 1
	$WhatAreFrog.is_bound = false
	$WhatAreFrog/LeashAnchor.visible = false
	$WhatAreFrog.remove_from_group("harmful")
	disconnect_rope()
	is_first_signal = false
