extends Area2D

@export var camera_to_limit: Camera2D
@export var auto_limit := true

func _ready() -> void:
	if camera_to_limit == null or !auto_limit or get_child_count() == 0:
		return
	
	var collision_shape: CollisionShape2D = get_children()[0]
	if collision_shape.shape is not RectangleShape2D:
		return
	
	var limits := _get_normalized_limits(collision_shape)
	camera_to_limit.limit_left = limits.position.x
	camera_to_limit.limit_top = limits.position.y
	camera_to_limit.limit_right = limits.end.x
	camera_to_limit.limit_bottom = limits.end.y


func _get_normalized_limits(collision_shape: CollisionShape2D) -> Rect2i:
	var rectangle_shape := collision_shape.shape as RectangleShape2D
	var rect_position := collision_shape.position
	var size := rectangle_shape.size
	var begin := rect_position - size / 2
	return Rect2(begin.x, begin.y, size.x, size.y)
