extends Node2D

@onready var spawnpoint = $Spawnpoint
@onready var blockContainer = $Blocks
@onready var gameTimer = $GameTimer

var partPath = "res://scenes/NewBlocks/part.tscn"

var nextBlocks =  []

var currentPattern = null

var patternsArray = []

var blockSpeed = 0.5

var stopped = false

#func _ready() -> void:
	#addBlocks()
	#for i in blockContainer.get_children():
		#i.init(i.global_position)

func _physics_process(delta: float) -> void:
	if GLOBAL.blockStopped:
		GLOBAL.testingPhase = true
		for i in $Rows.get_children():
			i.check()

		if $Borders/RayCast2D.is_colliding():
			GLOBAL.lose()
		spawnBlock()
		GLOBAL.testingPhase = false
		GLOBAL.blockStopped = false
		$TestTimer.start(0.2)
		

func startGame():
	fillNextBlocks()
	spawnBlock()
	GLOBAL.resetGame()
	match GLOBAL.currentMode:
		GLOBAL.MODES.INFINITE:
			GLOBAL.resetTime()
		GLOBAL.MODES.TIME:
			GLOBAL.setTimeModeTimer()
	gameTimer.start(1)

func _on_game_timer_timeout() -> void:
	match GLOBAL.currentMode:
		GLOBAL.MODES.INFINITE:
			GLOBAL.time += 1
		GLOBAL.MODES.TIME:
			if GLOBAL.time - 1 < 0:
				GLOBAL.lose()
			else:
				GLOBAL.time -= 1

	gameTimer.start(1)

func toggleButton():
	$Camera2D/CanvasLayer/Control.toggleButton()

func fillNextBlocks():
	var newBlocks = []
	for i in GLOBAL.BLOCKS:
		newBlocks.append(load(GLOBAL.BLOCKS[i]).instantiate())

	newBlocks.shuffle()
	newBlocks[0].expand = true
	newBlocks.shuffle()
	newBlocks[0].type = GLOBAL.BLOCKTYPES.HEAVY
	newBlocks.shuffle()
	nextBlocks.append_array(newBlocks)

func spawnBlock():
	GLOBAL.speedUp()
	var newBlock = nextBlocks[0]
	nextBlocks.pop_at(0)
	if nextBlocks == []:
		fillNextBlocks()
	blockContainer.add_child(newBlock)
	newBlock.init(spawnpoint.global_position)
	newBlock.setNewID()


func _on_test_timer_timeout() -> void:
	GLOBAL.rowRemoved = false
