extends Area2D

var enemy_type: String = "chicken"

var bullet_scene = preload("res://scenes/enemy_bullet.tscn")
var start_pos = Vector2.ZERO
var speed = 0
var tween_speed: float = 1.4

var exploding = false

var enemy_move_aggression = randf_range(5, 20)
var enemy_shoot_aggression = randf_range(4, 20)

@onready var screensize  = get_viewport_rect().size


func start(pos):
    speed = 0 
    position = Vector2(pos.x, -pos.y)
    start_pos = pos
    await get_tree().create_timer(randf_range(0.25, 0.55)).timeout
    var tween = create_tween().set_trans(Tween.TRANS_BACK)
    tween.tween_property(self, "position:y", start_pos.y, tween_speed)
    await tween.finished
    $MoveTimer.wait_time = enemy_move_aggression
    $MoveTimer.start()
    $ShootTimer.wait_time = enemy_shoot_aggression
    $ShootTimer.start()


func _on_timer_timeout() -> void:
  speed = randf_range(75, 100)

func _on_shoot_timer_timeout():
    var b = bullet_scene.instantiate()
    $Pew.play()
    get_tree().root.add_child(b)
    b.start(position)
    $ShootTimer.wait_time = randf_range(4, 20)
    $ShootTimer.start()

func _process(delta):
    position.y += speed * delta
    if position.y > screensize.y + 32:
        start(start_pos)


func hit_detection():
    if exploding: return
    exploding = true
    EventBus.enemy_hit.emit(5)
    speed = 0
    $AnimationPlayer.play("explode")
    $ChickenHit.play()
    #set_deferred("monitoring", false)
    await $AnimationPlayer.animation_finished
    queue_free()
    EventBus.enemy_died.emit()
 
