extends Node2D

export var squareNumber: int
export var nextLevel: String
export var backgroundColor: Vector3
export var finalLevel: bool

const absorb_rate: float = 10.0
const absorbed_size: Vector2 = Vector2(absorb_rate, absorb_rate)

var squareFilled = 0

var colorQuantity = {}
var squareQuantityNeeded = {}

func _ready() -> void:
	VisualServer.set_default_clear_color(Color(backgroundColor.x, backgroundColor.y, backgroundColor.z))
	InitializeQuantity()
	CheckQuantity()

func InitializeQuantity():
	for circle in $Circles.get_children():
		colorQuantity[str(circle.ball_color)] = 0
		squareQuantityNeeded[str(circle.ball_color)] = 0
	
	for circle in $Circles.get_children():
		colorQuantity[str(circle.ball_color)] += circle.size.x - 0.1
	for square in $Squares.get_children():
		squareQuantityNeeded[str(square.square_color)] += square.capacity
	print(colorQuantity)
	print(squareQuantityNeeded)

func CheckQuantity():
	for color in colorQuantity:
		if colorQuantity[color] < squareQuantityNeeded[color]:
			ResetLevel()

func RemoveQuantity(color, quantity):
	colorQuantity[color] -= quantity
	CheckQuantity()

func ResetLevel():
	$"Gravity Well/BlackHole".material.set_shader_param("color", Vector3(1, 1, 1))
	$"Gravity Well".gravity = -98
	get_tree().create_timer(0.75).connect("timeout", self, "ResetLevelNext")

func ResetLevelNext():
	$"Gravity Well/BlackHole".material.set_shader_param("color", Vector3(0, 0, 0))
	$"Gravity Well".gravity = 98
	get_tree().reload_current_scene()

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_cancel"):
		get_tree().reload_current_scene()

func SquareFilled():
	squareFilled += 1
	if squareFilled >= squareNumber:
		get_tree().change_scene(nextLevel)

func Collision(donor, receiver, delta: float):
		var corr_absorbed_size = absorbed_size * delta
		if donor.ball_color.is_equal_approx(receiver.ball_color):
			donor.size -= corr_absorbed_size;
			receiver.size += corr_absorbed_size;
		
		if donor.ball_color.inverted().is_equal_approx(receiver.ball_color):
			donor.size -= corr_absorbed_size
			colorQuantity[str(donor.ball_color)] -= absorb_rate * delta
			
			receiver.size -= corr_absorbed_size
			colorQuantity[str(receiver.ball_color)] -= absorb_rate * delta
			if not finalLevel:
				CheckQuantity()
