class_name StylizedNumberDisplay extends Control

@export var sprite_sheet: AtlasTexture
@export var number_sprite_width: int
@export var number_sprite_height: int
@export var value: int = 0:
	set(v):
		value = v
		if is_node_ready():
			_refresh()

@onready var _container: HBoxContainer = %HBoxContainer


func _ready() -> void:
	_refresh()


func _get_minimum_size() -> Vector2:
	var digit_count := str(absi(value)).length()
	var spacing: int = _container.get_theme_constant("separation") if is_node_ready() else 0
	var total_width: int = digit_count * number_sprite_width + maxi(digit_count - 1, 0) * spacing
	return Vector2(total_width, number_sprite_height)


func _refresh() -> void:
	for child in _container.get_children():
		child.queue_free()

	var digits := str(absi(value))
	for i in digits.length():
		var digit := digits[i].to_int()
		var atlas_tex := AtlasTexture.new()
		atlas_tex.atlas = sprite_sheet.atlas
		atlas_tex.region = Rect2(
			sprite_sheet.region.position.x + digit * number_sprite_width,
			sprite_sheet.region.position.y,
			number_sprite_width,
			number_sprite_height,
		)
		var tex_rect := TextureRect.new()
		tex_rect.texture = atlas_tex
		_container.add_child(tex_rect)
	update_minimum_size()
