extends Area2D

var enemy_type: String = "mirror"
var tween_speed: float = 1.4
var start_pos = Vector2.ZERO

var exploding = false
var health: int = 3
var pause: bool = false

@onready var screensize = get_viewport_rect().size
@onready var sink_player = $AnimationPlayer
@onready var impact_sound = $ImpactSound

func _ready() -> void:
  sink_player.seek(randf_range(5, sink_player.current_animation_length))
  EventBus.flash_screen.emit(0.15)
  

func start(pos):
  position = Vector2(pos.x, -pos.y)
  start_pos = pos
  var tween = create_tween().set_trans(Tween.TRANS_BACK)
  tween.tween_property(self, "position:y", start_pos.y, tween_speed)
 
#func _process(delta):
    #if pause == true: return



func hit_detection():
    if exploding: return
    
    if health != 0:
      health -= 1
      EventBus.enemy_hit.emit(5)
      var current_frame = get_node("Sprite").frame
      impact_sound.play()
      $Sprite.frame = current_frame + 1
    #$AnimationPlayer.play("explode")
    #set_deferred("monitoring", false)
    #await $AnimationPlayer.animation_finished
    var tween = create_tween().set_parallel(false)
    tween.tween_property($Sprite, "position:y", -2, 0.1)
    tween.tween_property($Sprite, "position:y", 0, 0.05)
    await tween.finished
    sink_player.pause()
    await get_tree().create_timer(0.25).timeout
    sink_player.play()
    
    if health == 0:
      exploding = true
      EventBus.flash_screen.emit(0.25)
      impact_sound.play()
      #await impact_sound.finished
      #find all nodes in group "shards" and then queue_free.
      var nodes = get_tree().get_nodes_in_group("shards")
      for node in nodes:
        node.queue_free()
      EventBus.enemy_died.emit()
      queue_free()
      
    
      
      
func explode():
    if exploding: return
    #exploding = true
    EventBus.enemy_hit.emit(5)
    hit_detection()
    #$ImpactCRT.play()
    #$AnimationPlayer.play("explode")
    #set_deferred("monitoring", false)
    #await $AnimationPlayer.animation_finished
    #queue_free()
    #EventBus.enemy_died.emit()
