extends Node2D

@onready var spriteBlock = $Sprites/Block
@onready var spriteSpecialBlock = $Sprites/SpecialBlock
@onready var spriteExpandBlock = $Sprites/ExpandBlock
@onready var spriteSpecialExpandedBlock = $Sprites/SpecialExpandedBlock

@onready var rayTop = $Raycasts/RayTop
@onready var rayRight = $Raycasts/RayRight
@onready var rayBottom = $Raycasts/RayBottom
@onready var rayLeft = $Raycasts/RayLeft

#func _physics_process(delta: float) -> void:
	##if GLOBAL.blockStopped and not GLOBAL.rowRemoved:
	#if GLOBAL.currentID != get_parent().get_parent().id:
		#removeOverlapp()

func isOverlapping() -> bool:
	var collided = false
	for i in get_children():
		if is_instance_of(i,RayCast2D):
			i.force_raycast_update()
			var collider = i.get_collider()
			if collider != null:
				collided = true
	return collided

func removeOverlapp():
	var blocksSplit = []
	for i in get_children():
		if is_instance_of(i,RayCast2D):
			i.force_raycast_update()
			var collider = i.get_collider()
			if collider != null and collider.get_parent().get_parent().id != GLOBAL.currentID:
				blocksSplit.append(i.get_collider().get_parent().get_parent())
				collider.free()
	for j in blocksSplit:
		j.splitParts()
		
func init(pos, look=0):
	position = pos
	match look:
		0:
			spriteBlock.show()
		1:
			spriteSpecialBlock.show()
		2:
			spriteExpandBlock.show()
		3:
			spriteSpecialExpandedBlock.show()


func isTopColliding():
	rayTop.force_raycast_update()
	if rayTop.get_collider() == null:
		return false
	
	elif rayTop.get_collider().is_in_group("Block"):
		if rayTop.get_collider().id == GLOBAL.currentID:
			return false
		else:
			return true
	else:
		return true

func isRightColliding():
	rayRight.force_raycast_update()
	#print(rayRight.get_collider())
	if rayRight.get_collider() == null:
		return false
	elif rayRight.get_collider().is_in_group("Block"):
		#print(rayRight.get_collider().id)

		if rayRight.get_collider().id == GLOBAL.currentID:
			return false
		else:
			return true
	else:
		return true
	
func isBottomColliding():
	rayBottom.force_raycast_update()
	if rayBottom.get_collider() == null:
		return false
	
	elif rayBottom.get_collider().is_in_group("Block"):
		if rayBottom.get_collider().id == GLOBAL.currentID:
			return false
		else:
			return true
	else:
		return true

func isLeftColliding():
	
	rayLeft.force_raycast_update()
	#print(rayLeft.get_collider())
	if rayLeft.get_collider() == null:
		return false
	
	elif rayLeft.get_collider().is_in_group("Block"):
		#print(rayLeft.get_collider().id)
		if rayLeft.get_collider().id == GLOBAL.currentID:
			return false
		else:
			return true
	else:
		return true
