extends TileMap

enum TileType {WALL = 2, BLANK = 3, HOLE = 4, STOP = 5}

const tileTable: Array = [TileType.BLANK,TileType.BLANK,TileType.WALL,TileType.HOLE,TileType.STOP]
var cellGraph: Array
var nextRow: int = -1

func _ready() -> void:
	generate(get_used_cells())
	
func generate(cells: Array):
	for cell in cells:
		var tile: int = tileTable[rand_range(0,tileTable.size())]
		set_cellv(cell,tile)
		
	for cell in cells:
		var cellGraphData: CellGraphData = CellGraphData.new()
		cellGraphData.cell = cell
		
		for x in range(-1,2):
			for y in range(-1,2):
				if (x == 0 && y == 0):
					continue
				var tile: int = get_cellv(cell)
				if (tile == TileType.WALL || tile == TileType.HOLE):
					continue
				var move: Vector2 = find_move(cell, Vector2(x,y))
				if (move == cell):
					continue
				var moveTile: int = get_cellv(move)
				if (moveTile == TileType.WALL || moveTile == TileType.HOLE): 
					continue
				cellGraphData.links.append(move)
		
		cellGraph.append(cellGraphData)

func map_pos(grid: Vector2) -> Vector2:
	return cell_size * grid

func find_move(from: Vector2, dir: Vector2) -> Vector2:
	var curPos: Vector2 = from
	var cont: bool = true
	
	while (cont):
		var nextPos: Vector2 = curPos + dir
				
		var nextCell: int = get_cellv(nextPos)
		if (nextCell == TileType.WALL): # wall
			return curPos
		elif (nextCell == TileType.STOP || nextCell == TileType.HOLE): # stop or hole
			return nextPos
		elif (nextCell == TileMap.INVALID_CELL):
			return nextPos
		else:
			curPos = nextPos
	
	return Vector2(-1,-1)
	
func _process(delta: float) -> void:
	position.y += delta * 3
	
	if (position.y > (cell_size.y * abs(nextRow))):
		print("Generating row " + String(nextRow))
		nextRow += 1
		var toGenerate: Array = []
		for x in range(get_used_rect().size.x):
			toGenerate.append(Vector2(x,-nextRow))
			
		generate(toGenerate)

class CellGraphData:
	var cell: Vector2
	var links: Array
