extends RayCast3D

var spawned = false
var inside_wall = false
@onready var wall_tester = $WallTester
var ticks_for_spawn = 3
var triggered = false
@export var trigger_on_start = false
@export var one_time = true
var last_spawned_object = null
@export var obj_to_instance: PackedScene = load("res://entities/objects/stone_pile/StonePile.tscn")


func _ready() -> void:
	pass
		
func _physics_process(delta: float) -> void:
	
	ticks_for_spawn -=1
	if ticks_for_spawn <= 0:

		if (one_time and spawned) or inside_wall:
			return
		

		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():
						if trigger_on_start == true or triggered == true:
							print ("spawning now...")
							spawn_object()
							spawned = true
							
							trigger_on_start = false
							triggered = false
					else:
						print ("overlapping body found: not spawning")
				else:
					print ("below acid level: not spawning")

#fixme: it almost works as general spawner code, only with gridbasedmovable objects not
func spawn_object():
	if is_colliding():

		var obj_instance = obj_to_instance.instantiate()
		var game = SceneManager.game_scene
		var level = game.level_scene_instance
		game.add_child(obj_instance)
		obj_instance.position = get_collision_point()
		last_spawned_object = obj_instance
		#puddle_instance.cleaned.connect(Callable(level, "_on_puddle_cleaned"))
		#level.new_puddle_added()

func trigger():
	print ("object spawner triggered..")
	
	if is_colliding():
		var obj = get_collider()
		if obj.is_class("GridMap"):
			triggered = true
			

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



