extends TileMap
class_name CustomTileMap

var astar : AStarGrid2D = AStarGrid2D.new()
@onready var fog_overlay : ColorRect = $FogOverlay

@onready var tilemap_size : Vector2i = get_used_rect().end - get_used_rect().position
@onready var map_rect : Rect2i = Rect2i(Vector2i.ZERO, tilemap_size)

var mushroom_glow : PackedScene = load("res://entities/mushroom_glow.tscn")

var highlighted_tiles : Array = []

# Has a signal to indicate the tilemap has been updated 
signal tilemap_updated

func _ready() -> void:

	var tile_size : Vector2i  = get_tileset().tile_size
	var map_pixel_size : Vector2i = tilemap_size * tile_size
	fog_overlay.size = map_pixel_size


	setup_pathing()
	# check_for_visible_gatherables()
	emit_signal('tilemap_updated')
	pass

func setup_pathing() -> void:
	# Setup the AStarGrid2D for pathfinding
	var tile_size : Vector2i = get_tileset().tile_size 

	Log.pr("Tilemap size: " + str(tilemap_size))

	astar.region = map_rect 
	astar.cell_size = tile_size 
	astar.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN
	astar.default_estimate_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN
	astar.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
	astar.update()

	update_passable()
	
	pass

func update_passable() -> void:
	# Update the AStarGrid2D with the new passable tiles
	for i in tilemap_size.x:
		for j in tilemap_size.y:
			var coords : Vector2i = Vector2i(i, j)
			var tile_data : TileData = get_cell_tile_data(get_layer_id_by_name('Floor'), coords)
			if tile_data and tile_data.get_custom_data('navtype') == 'wall':
				astar.set_point_solid(coords)
				continue

			tile_data = get_cell_tile_data(get_layer_id_by_name('Water'), coords)
			if tile_data and tile_data.get_custom_data('navtype') == 'water':
				astar.set_point_solid(coords)
				continue
			
			astar.set_point_solid(coords, false)
	pass

func is_point_walkable(check_position : Vector2i) -> bool:
	var map_position : Vector2i = local_to_map(check_position)
	if map_rect.has_point(map_position) and not astar.is_point_solid(map_position):
		return true
	
	return false

func _unhandled_input(event : InputEvent) -> void:
	pass
	if event.is_action_pressed("move_to"):
		var click_position : Vector2 = get_global_mouse_position()
		var tile_position : Vector2i = local_to_map(click_position)

		## Check if the clicked tile is a wall 

		## Get the surrounding wall tiles and redraw them 
		## We spread to a 3x3 area for blowing up walls because it was very 
		## weird with 1x1 cells
		var update_cells : Array = GridUtil.get_surrounding_tiles(tile_position)
		update_cells = filter_indestructible_tiles(update_cells)
		set_cells_terrain_connect(0, update_cells, 0, 0)

		## Get all the co-ordinates around the given tile_position coordinates 
		## This will redraw the surrounding cells to make the terrains look better
		var surrounding_cells : Array = GridUtil.get_surrounding_tiles(tile_position, 5)
		redraw_surrounding_tiles(surrounding_cells)

		update_passable()
		## Emit event to update the mushroom glowies
		emit_signal('tilemap_updated')


func redraw_surrounding_tiles(positions : Array) -> void:
	var walls : Array = []

	for cell_pos : Vector2 in positions:
		var tile_data : TileData = get_cell_tile_data(0, cell_pos)
		if tile_data and tile_data.get_custom_data('navtype') == 'wall' and tile_data.get_custom_data('indestructible') != true:
			walls.append(cell_pos)

	set_cells_terrain_connect(0, walls, 0, 1)

func filter_indestructible_tiles(coords : Array) -> Array:
	var filtered_coords : Array = []
	for coord : Vector2 in coords:
		var tile_data : TileData = get_cell_tile_data(0, coord)
		if tile_data and tile_data.get_custom_data('indestructible') != true:
			filtered_coords.append(coord)

	return filtered_coords

func get_layer_id_by_name(level_name : String) -> int:
	var layers : int = get_layers_count()
	for i in layers:
		if get_layer_name(i) == level_name:
			return i
	return -1