extends Node2D

## MAP VARIABLES
var GRID_WIDTH = Global.GRID_WIDTH
var GRID_HEIGHT = Global.GRID_HEIGHT
var EMPTY = Global.MAP_EMPTY
var PATH = Global.MAP_PATH
var START = Global.MAP_START
var FINISH = Global.MAP_FINISH
var UP_CELL = Global.MAP_UP_CELL

## MAP LAYERS
var ground: TileMapLayer
var water: TileMapLayer
var walls: TileMapLayer
var scatter: TileMapLayer
var cells: Array

## MAP
var map: Array

var map_width: int
var map_height: int

func _ready() -> void:
	Log.pr("Level ready")

	map_width = Global.GRID_WIDTH * Global.ROOM_WIDTH
	map_height = Global.GRID_HEIGHT * Global.ROOM_HEIGHT

	ground = $Ground
	water = $Water
	#walls = $Walls
	scatter = $Scatter

	cells = CoordUtil.all_cells(Vector2i(-1, -1), Vector2i(map_width + 1, map_height + 1))

	#RNG.set_seed(123456789)
	Log.pr(RNG.get_seed())
	Log.pr(RNG.randf())
	Log.pr(RNG.randf())
	Log.pr(RNG.randf())
	Log.pr(RNG.randf())
	#RNG.set_seed(123456789)
	Log.pr(RNG.get_seed())
	Log.pr(RNG.randf())
	Log.pr(RNG.randf())
	Log.pr(RNG.randf())
	Log.pr(RNG.randf())
	generateMap()

func generateMap() -> void:
	Log.pr("Generating map")

	var map_generator = MapGenerator.new()
	map_generator.generate_map()
	map_generator.print_map()

	map = map_generator.get_map()
	Log.pr(map)

	drawGround()
	drawPerimiter()
	populateMapCells()

func drawGround() -> void:
	Log.pr("Drawing ground")
	ground.clear()
	ground.set_cells_terrain_connect(cells, 0, 0, false)

func drawPerimiter() -> void:
	Log.pr("Drawing perimeter")
	var perimeter_cells: Array = CoordUtil.perimeter_cells(Vector2i(0, 0), Vector2i(map_width - 1, map_height - 1), false, 2)
	water.set_cells_terrain_connect(perimeter_cells, 0, 1, false)

func populateMapCells() -> void:
	# Loop through the map and check which type of cell it is 
	Log.pr("Populating map cells")
	for y in range(GRID_HEIGHT):
		for x in range(GRID_WIDTH):
			var cell_value = map[y][x]

			var scene = null

			match cell_value:
				EMPTY:
					scene = SceneSelector.get_random_scene("res://mapgen/layout/misc")
					Log.pr("Empty cell ", y, x, scene)
				PATH:
					scene = SceneSelector.get_random_scene("res://mapgen/layout/path")
					Log.pr("Path cell", y, x, scene)
				START:
					scene = SceneSelector.get_random_scene("res://mapgen/layout/start")
					Log.pr("Start cell", y, x, scene)
				FINISH:
					scene = SceneSelector.get_random_scene("res://mapgen/layout/finish")
					Log.pr("Finish cell", y, x, scene)
				UP_CELL:
					scene = SceneSelector.get_random_scene("res://mapgen/layout/link")
					Log.pr("Up cell", y, x, scene)
			
			MapBuilder.copy_tilemap_to_target(scene, water, "Water", Vector2i(x, y))
			MapBuilder.copy_tilemap_to_target(scene, scatter, "Scatter", Vector2i(x, y))
	#walls.set_cells_terrain_connect(cells, 0, 0, true)
	MapBuilder.redraw_terrain(cells, water, 0, 1)
