@tool
extends "res://entities/GridBasedMovable.gd"


var disposed = false
@export var damaged = false: set = set_damaged
@onready var mesh_instance_damaged = $RotationPoint/MeshInstanceDamaged

@onready var audio_player = $AudioStreamPlayer3D


signal barrel_disposed



func dispose():
	if disposed:
		return
	
	emit_signal("barrel_disposed")
	enable_movement = false
	disposed = true

func set_damaged(_damaged: bool):
	damaged = _damaged
	if Engine.is_editor_hint():
		if _damaged == true:
			set_damage_material(true)
		else:
			set_damage_material(false)


func _ready() -> void:
	if damaged:
		set_damage_material(true)
	
	if Engine.is_editor_hint():
		return
	
	super._ready()
	

func _physics_process(delta):
	if Engine.is_editor_hint():
		return
	
	_handle_movement(delta)

	if disposed and timer.time_left < 0.05:
		call_deferred("queue_free")

func set_damage_material(_damaged):
	if mesh_instance_damaged == null or mesh_instance == null:
		return
	if _damaged == true:
		mesh_instance.visible = false
		mesh_instance_damaged.visible = true
	else:
		mesh_instance.visible = true
		mesh_instance_damaged.visible = false
	
	

func _on_Health_no_health() -> void:
	hit()

func hit():
	if damaged:
		explode()
	else:
		take_damage()
	

func take_damage():
	if Engine.is_editor_hint():
		return
	spread_puddles()
	if damaged:
		return
	damaged = true
	set_damage_material(true)
	print ("barrel taking damage now")

func explode():
	if Engine.is_editor_hint():
		return

	var Explosion = load("res://entities/Explosion.tscn")
	var explosion_instance = Explosion.instantiate()
	var game = SceneManager.game_scene
	game.add_child(explosion_instance)
	explosion_instance.position = position
	print ("explosion at: " + str(position))
	
	take_damage()
	dispose()

func spread_puddles():
	if Engine.is_editor_hint():
		return
		
	var Spreader = load("res://entities/PuddleSpreader.tscn")
	var spreader_instance = Spreader.instantiate()
	var game = SceneManager.game_scene
	game.add_child(spreader_instance)
	spreader_instance.position = position
	print ("spreading puddles at: " + str(position))
		#audio_player.volume_db = -1
	audio_player.pitch_scale = randf_range(0.86, 0.93)
	audio_player.play()
