class_name PushableBox
extends RigidBody2D

var _corresponding_box_in_present: PushableBox  # the "if _corresponding_box_in_present:" is to check if this is the past version of the box
var own_id: int = 0
var old_pos: Vector2


func _ready() -> void:
	# allowing multiple boxes in 1 scene . rn up to 3
	if is_in_group("PushableBox1"):
		own_id = 1
	elif is_in_group("PushableBox2"):
		own_id = 2
	elif is_in_group("PushableBox3"):
		own_id = 3
		
	old_pos = position
		
	# it's jank, but otherwise the id assignment isnt done by the time other boxes are already trying to find their partner
	if is_inside_tree():
		await get_tree().create_timer(0.1).timeout  
	# connect corresponding box in past and present
	_connect_past_and_present_boxes()
	
	
func _process(_delta: float) -> void:
	# if past changed pos tell the corresponding present box
	if _corresponding_box_in_present and old_pos != position:
		_corresponding_box_in_present.position = position
		old_pos = position  

func _connect_past_and_present_boxes():
	var found_boxes_in_present = get_tree().get_nodes_in_group("CorrespondingPushableBoxInPresent")
	for box in found_boxes_in_present:
		if box == self:
			return
		if box.own_id == own_id:
			#print("same id!!", box.name, name)
			_corresponding_box_in_present = box
