extends Node2D
class_name MushroomGlowComponent

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

@export var tile_map : CustomTileMap = null
@onready var mushroom_glow_container : Node2D = $MushroomGlowContainer
var glowing_mushrooms : Array = []

var tile_size : Vector2i
var map_pixel_size : Vector2i
var tilemap_size : Vector2i 
var mushroom_layer : int = -1

func _ready()  -> void:
	if !tile_map:
		Log.err("MushroomGlowComponent: TileMap not set")

	Log.pr("MushroomGlowComponent ready")

	tile_map.tilemap_updated.connect(add_mushroom_glow)

	tile_size = tile_map.get_tileset().tile_size
	map_pixel_size = tilemap_size * tile_size
	tilemap_size = tile_map.get_used_rect().end - tile_map.get_used_rect().position

	mushroom_layer = tile_map.get_layer_id_by_name('Mushrooms')
	Log.pr(mushroom_layer)
	add_mushroom_glow()

## Look for crystals in the scene and add the glow to the approprirate angle and colour
func add_mushroom_glow() -> void:
	for i in tilemap_size.x:
		for j in tilemap_size.y:
			var coords : Vector2i = Vector2i(i, j)

			## If this coord is glowing already then we dont need to do anything
			if coords in glowing_mushrooms:
				continue
			else:
				var tile_data : TileData = tile_map.get_cell_tile_data(mushroom_layer, coords)
				if tile_data:
					# Get the tile data from the base layer 
					var below_tile_data : TileData = tile_map.get_cell_tile_data(tile_map.get_layer_id_by_name('Floor'), coords)
					if below_tile_data and below_tile_data.get_custom_data('navtype') == 'wall':
						pass
					else:
						if tile_data.get_custom_data('glowcolour'):
							var glow_colour : String = tile_data.get_custom_data('glowcolour')
							var glow : MushroomGlow = mushroom_glow.instantiate()
							glow.set_position(coords * tile_map.get_tileset().tile_size + tile_map.get_tileset().tile_size / 2)
							glow.colour_name = glow_colour
							mushroom_glow_container.add_child.call_deferred(glow)
							glowing_mushrooms.append(coords)

