extends RigidBody2D

@export_category("Basic Stuff")
@export var Speed: int = 250
@export var Health: int = 5
@export var Direction: Vector2 = Vector2(-1, 0)
@export var ScoreAmount: int = 200

@export_category("Shooting")
@export var IsShooting: bool = false
@export var Bullet: PackedScene
@export var FireSpeed: float = 1
@export_range(0, 360) var BulletDirection: float = 0
var FireTimer: float = 0

@export_category("Other")
@export var IsBoss: bool = false

var DespawnTimer: float = 0

func _ready():
	get_node("Arm").rotation_degrees = -BulletDirection
	if Direction.x == 1:
		get_node("AnimatedSprite2D").flip_h = true

func _integrate_forces(_state: PhysicsDirectBodyState2D):
	self.linear_velocity = Direction * Speed

func _process(delta: float):
	# Despawning
	DespawnTimer += delta
	
	# Despawn to free up processing time
	if DespawnTimer >= 30 and IsBoss == false:
		self.queue_free()
	
	# Shooting
	if IsShooting == true:
		FireTimer += delta
		if FireTimer >= FireSpeed:
			var bullet = Bullet.instantiate()
			bullet.rotato = -BulletDirection + 180
			bullet.transform = get_node("Arm/Marker2D").global_transform
			get_tree().current_scene.add_child(bullet)
			FireTimer = 0
	
	# Death
	if Health <= 0:
		Global.TotalScore += ScoreAmount
		if IsBoss == true:
			Despawn()
		else:
			self.queue_free()

# FOR ANIMATION ONLY
func Despawn():
	self.queue_free()
	# Laziness. Gets the waves.
	get_tree().current_scene.get_node("EnemyWaves").WaveWaits[get_tree().current_scene.get_node("EnemyWaves").CurrentWave] = 0
