extends Node3D

var gas_square_template = preload("res://templates/gas_square.tscn")
var cycles : int = 3
var square : Vector3i = Vector3i(2,0,0)
var squares : Dictionary[Vector3i, bool] = {}
var last_spread : Array[Vector3i]
var trap_owner : int
var damage : int = 4

func _ready() -> void:
	emit_gas.call_deferred(square)
	last_spread = [square]
	squares[square] = true

func _on_timeout() -> void:
	cycles -= 1
	if cycles <= 0:
		queue_free()
		return
	spread()

func spread() -> void:
	var new_squares : Dictionary[Vector3i, bool] = {}
	for square in last_spread:
		for i in range(-1, 2):
			for j in range(-1, 2):
				for k in range(-1, 2):
					var ts = square + Vector3i(i, j, k)
					new_squares[square + Vector3i(i, j, k)] = true
	last_spread = []
	for square in new_squares.keys():
		if squares.has(square):
			continue
		var floor_square = square + Vector3i(0,-1,0)
		if(Game.level.floor_layer.get_cell_item(floor_square) == GridMap.INVALID_CELL_ITEM
		and Game.level.ramp_layer.get_cell_item(floor_square) == GridMap.INVALID_CELL_ITEM):
			continue
		last_spread.append(square)
		squares[square] = true
		emit_gas(square)

func emit_gas(square) -> void:
	var gas = gas_square_template.instantiate()
	gas.setup(trap_owner, damage)
	Game.level.add_vfx(gas, square)
