class_name Bolt
extends Node2D

@export var pushback_speed: float = 100.0
@export var speed: float = 500.0
@export var damage:int = 1
@export var detector: Area2D

@onready var area_collision_shape: CollisionShape2D
@onready var sprite: Sprite2D = $Sprite2D


var fired:bool = false:
	get: return fired
var alive:bool = true:
	get: return alive

func fire(dir:Vector2):
	if fired || !alive: return
	fired = true
	#await get_tree().process_frame
	area_collision_shape = detector.get_child(0)
	detector.body_entered.connect(_on_hit)
	global_rotation = dir.angle() + PI / 2.0

func _process(delta: float) -> void:
	if fired && alive:
		global_position += -transform.y * speed * delta

func _on_hit(body:Node2D):
	alive = false

	area_collision_shape.set_deferred("disabled", true)
	
	var entity:Entity = body as Entity
	if entity:
		entity.damage(damage)
		entity.push(-transform.y * pushback_speed)
		entity.attach_bullet.call_deferred(self)
	else:
		$ArrowHit.play()
		self.modulate.a = 0.75
		var tw = create_tween().set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_QUART)
		tw.tween_property(self, "modulate:a", 0.0, 10.0)
		tw.tween_callback(func(): queue_free())
