extends Area2D

class_name Loop;

var entered_count := 0;
var target_character : Character;
var shadow_resource := load("res://objects/shadow.tscn");
var shadow_created : Shadow;

@onready
var count_name = {$SpriteOff : 0, $SpriteRecording : 1, $SpriteOn : 2};

var move_list : Array[Globals.Direction];
var is_recording := false;
var is_playing := false;
var is_off := true; 

var shadow_exist := false;


func _process(delta: float) -> void:
	pass

func _on_area_entered(area: Area2D) -> void:
	if area == shadow_created:
		return;
	entered_count += 1;
	entered_count %= 3;
	is_recording = entered_count == 1;
	is_playing = entered_count == 2;
	is_off = entered_count == 0;
	
	if is_playing and !shadow_created:
		shadow_created = shadow_resource.instantiate();
		shadow_created.loop_origin = self;
		shadow_created.position = self.position;
		get_tree().current_scene.add_child(shadow_created);
		
	if is_off:
		shadow_created.queue_free();
		shadow_created = null;
		move_list.clear()
		
		
		
		
	
	connect_target_character(area)
	handle_visibility()
	


func connect_target_character(area: Area2D):
	if area is Character and !target_character:
		target_character = area
		target_character.has_moved.connect(_on_target_moved);
		print(target_character.has_moved.get_connections());
	

func handle_visibility():
	for name in count_name:
		if count_name[name] == entered_count:
			name.visible = true;
		else:
			name.visible = false;
			

func _on_target_moved(direction: Globals.Direction):
	if is_recording:
		move_list.push_back(direction)
		print(move_list)
	
