class_name Building
extends CollisionObject3D

@export var health := 10.

@export var shake_noise: FastNoiseLite
@export var randomize_height := true
var shake_duration := 0.
@onready var initial_shaker_pos: Vector3 = %Shaker.position

signal destroyed_from(global_pos: Vector3)

func _ready() -> void:
	if randomize_height:
		scale.y = randf_range(.5, 1.25)


func _process(delta: float) -> void:
	if shake_duration <= 0:
		%Shaker.position = initial_shaker_pos
	else:
		var x := shake_noise.get_noise_1d(shake_duration * 10000)
		var y := shake_noise.get_noise_1d(-shake_duration * 10000)
		%Shaker.position = initial_shaker_pos + (Vector3(x, 0, y) * 0.75)
	
	shake_duration = move_toward(shake_duration, 0., delta)

func _show_score_label(score: int) -> void:
	%ScoreLabel.position.x += randf_range(-2, 2)
	%ScoreLabel.position.y += randf_range(-2, 2)
	%ScoreLabel.text = "+%d" % score
	%ScoreLabel.show()
	create_tween().tween_property(%ScoreLabel, "position:y", %ScoreLabel.position.y + 2., 1.)
	await get_tree().create_timer(.5, false).timeout

	var t := create_tween()
	t.tween_property(%ScoreLabel, "modulate:a", 0., .5)
	t.parallel().tween_property(%ScoreLabel, "outline_modulate:a", 0., .5)
	t.finished.connect(%ScoreLabel.queue_free)


func hit(proj: Node3D, damage: float) -> bool:
	health -= damage
	if health <= 0.:
		var score := randi_range(10, 20)
		SignalBus.building_destroyed.emit(self, score)
		destroyed_from.emit(proj.global_position)
		collision_layer = 1 # World collision only

		%Shaker.hide()
		%DestroyedMesh.show()
		%GPUParticles3D.preprocess = randf()

		_show_score_label(score)

	else:
		shake_duration += 0.5

	return true
