extends Node2D
class_name WaterEffectComponent


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

@export var tile_map : CustomTileMap = null
@onready var water_effect_container : Node2D = $WaterEffectContainer

var effect_tiles : Array = []

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

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

	Log.pr("WaterEffectComponent 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

	water_layer = tile_map.get_layer_id_by_name('Water')
	Log.pr(water_layer)
	add_water_effects()

## Look for crystals in the scene and add the glow to the approprirate angle and colour
func add_water_effects() -> 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 effect_tiles:
				continue
			else:
				var tile_data : TileData = tile_map.get_cell_tile_data(water_layer, coords)
				if tile_data:
					if tile_data.get_custom_data('glowcolour'):
						var is_it_water : String = tile_data.get_custom_data('glowcolour')
						if is_it_water == 'water':

							## 10% chance to add fog 
							if randf() < 0.1:
								var fog : WaterFog = water_fog.instantiate()
								fog.set_position(coords * tile_map.get_tileset().tile_size + tile_map.get_tileset().tile_size / 2)
								water_effect_container.add_child.call_deferred(fog)
								effect_tiles.append(coords)


							## 20% chance to add water particles
							if randf() < 0.2:
								var water : WaterParticles = water_particles.instantiate()
								water.set_position(coords * tile_map.get_tileset().tile_size + tile_map.get_tileset().tile_size / 2)
								water_effect_container.add_child.call_deferred(water)
								effect_tiles.append(coords)



