extends RayCast3D


var spawned = false
var inside_wall = false
@onready var wall_tester = $WallTester
@onready var spawner_tester = $SpawnerTester
var ticks_for_spawn = 3


func _ready() -> void:
	pass
		
func _physics_process(delta: float) -> void:
	ticks_for_spawn -=1
	if ticks_for_spawn <= 0:
		if spawned or inside_wall:
			return
		spawned = true

		if is_colliding():
			var collided_with = get_collider()
			if collided_with.is_class("GridMap"):
				print(get_collision_point())
				if get_collision_point().y > 0.2:
					if !wall_tester.has_overlapping_bodies():
						spawn_puddle()
					else:
						print ("overlapping body found: not spawning")
				else:
					print ("below acid level: not spawning")

func spawn_puddle():

	if is_colliding():
		var Puddle = load("res://entities/objects/puddle/Puddle.tscn")
		var puddle_instance = Puddle.instantiate()
		var game = SceneManager.game_scene
		var level = game.level_scene_instance
		game.add_child(puddle_instance)
		puddle_instance.position = get_collision_point()
		puddle_instance.cleaned.connect(Callable(level, "_on_puddle_cleaned"))
		level.new_puddle_added()
		


func _on_WallTester_body_entered(body: Node3D) -> void:
	print("inside wall!!!")
	print (body.name)
	inside_wall = true






func _on_spawner_tester_area_shape_entered(area_rid: RID, area: Area3D, area_shape_index: int, local_shape_index: int) -> void:
	if area_rid < spawner_tester.get_rid():
		print ("oh - should not spawn double puddles")
		if area.get_parent().has_method("spawn_puddle"):
			area.get_parent().spawned = true
