extends Node2D


export var ammo:int = 1
export var timeout:= 2.0
export var enabled := true 

var _activated := false
var _can_activate := true
onready var _ammo = ammo
var Arrow = load("res://src/Hazards/Arrow.tscn")


func _ready() -> void:
  GameState.connect("player_just_died", self,"_on_Player_died")
func _physics_process(delta: float) -> void:
  if enabled && _can_activate && _did_trigger():
    _can_activate = false
    _activated = true
    $AnimationPlayer.play("fire")


func _did_trigger()->bool:
  if $TopRayCast.is_colliding():
    var collider = $TopRayCast.get_collider()
    if collider.name == "SolidsTileMap":
      var new_cast = $TopRayCast.cast_to
      new_cast.x =  to_local($TopRayCast.get_collision_point()).x - 1      
      $TopRayCast.cast_to = new_cast
    if collider.name == "Player":
      return true
  if $BottomRayCast.is_colliding():
    var collider = $BottomRayCast.get_collider()
    if collider.name == "SolidsTileMap":
      var new_cast = $BottomRayCast.cast_to
      new_cast.x =  to_local($BottomRayCast.get_collision_point()).x - 1      
      $BottomRayCast.cast_to = new_cast
    if $BottomRayCast.get_collider().name == "Player":
      return true
  return false




func _on_fire_animation_ended():
  print("Fire!")
  var arrow = Arrow.instance()
  arrow.position = Vector2(8,-3)
  add_child(arrow)
  _ammo -= 1
  if _ammo == 0:
    $AnimationPlayer.play("idle")
    _activated = false
    $TimeoutTimer.start(timeout)
  else:
	  $AnimationPlayer.play("fire")


func play_sfx():
  AudioManager.play_sfx(AudioManager.Sfx.MASK_FIRE)

func _on_TimeoutTimer_timeout()->void:
  _can_activate = true;
  $AnimationPlayer.play("armed")
  _ammo = ammo

func _on_Player_died():
  $AnimationPlayer.play("idle")
  _activated = false
  $TimeoutTimer.start(timeout)