extends Polygon2D

export var capacity: float = 1.0

const rate: float = 2.0

var quantity: float = 0
var filled = false
var body_entered = []
var square_color: Color

func set_shader_quantity():
	material.set_shader_param("quantity", quantity / capacity)

func _ready() -> void:
	var color: Vector3 = material.get_shader_param("color")
	square_color = Color(color.x, color.y, color.z)
	set_shader_quantity()

func _physics_process(delta: float) -> void:
	if not filled and not body_entered.empty():
		var absorbed: float = rate * delta
		for body in body_entered:
			body.size -= Vector2(absorbed, absorbed)
			quantity += absorbed
			set_shader_quantity()
			if quantity >= capacity:
				filled = true
				get_parent().get_parent().SquareFilled()
				return

func _on_SquareBody_body_entered(body: Node) -> void:
	if body.is_in_group("Circle"):
		if body.ball_color.is_equal_approx(square_color):
			body_entered.append(body)

func _on_SquareBody_body_exited(body: Node) -> void:
	if body.is_in_group("Circle"):
		if body.ball_color.is_equal_approx(square_color):
			body_entered.erase(body)
