extends Node2D
class_name CrystalGlowComponent

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

@export var tile_map : CustomTileMap = null
@onready var crystal_glow_container : Node2D = $CrystalGlowContainer
var glowing_crystals : Array = []

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

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

	Log.pr("CrystalGlowComponent ready")

	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

	crystal_layer = tile_map.get_layer_id_by_name('Crystals')
	Log.pr(crystal_layer)
	add_crystal_glow()

## Look for crystals in the scene and add the glow to the approprirate angle and colour
func add_crystal_glow() -> void:
	for i in tilemap_size.x:
		for j in tilemap_size.y:
			var coords : Vector2i = Vector2i(i, j)
			var tile_data : TileData = tile_map.get_cell_tile_data(crystal_layer, coords)
			if tile_data:
				if tile_data.get_custom_data('glowcolour'):
					var glow_colour : String = tile_data.get_custom_data('glowcolour')
					var orientation : String = tile_data.get_custom_data('orientation')

					# Check if this coord is already in the glowing_crystals array
					if coords in glowing_crystals:
						continue
					else:
						var glow : CrystalGlow = crystal_glow.instantiate().duplicate()
						glow.set_position(coords * tile_map.get_tileset().tile_size + tile_map.get_tileset().tile_size / 2)
						glow.glow_colour = glow_colour
						glow.orientation = orientation
						crystal_glow_container.add_child(glow)
						glowing_crystals.append(coords)

	Log.pr("Glowing crystals: ", glowing_crystals)