class_name DynamicGridContainer
extends GridContainer


var _item_size := Vector2.ZERO
onready var MIN_H_SEPERATION: int = get_constant("hseparation")


func _ready() -> void:
	connect("resized", self, "_on_resized")
	
	_rearrange()


func set_item_size(item_size: Vector2) -> void:
	_item_size = item_size


func _rearrange() -> void:
	"""
	Rearranges the child controls so that the maximum number of columns are 
	used that fit within the width of this control and any left over space is 
	spread between the controls as padding
	"""
	if _item_size.x < 0.01:
		set_columns(1)
		return
	
	var new_column_count: int = 1
	var content_width: float = _item_size.x
	while content_width < get_size().x:
		new_column_count += 1
		content_width += MIN_H_SEPERATION + _item_size.x
	if new_column_count > 1:
		# Undo 1 step to prevent items exceeding the width of the container
		new_column_count -= 1
		content_width -= MIN_H_SEPERATION + _item_size.x
	
	var spare_space: float = max(0, get_size().x - 1 - content_width)
	add_constant_override("hseparation", int(MIN_H_SEPERATION + (spare_space / new_column_count)))
	set_columns(new_column_count)


func _on_resized() -> void:
	_rearrange()
