using System.Threading.Tasks;
using Godot;

public partial class Gun : Node3D
{
  [Export]
  public int MaxAmmo;

  [Export]
  public double DamagePerHit;

  [Signal]
  public delegate void OnHitEventHandler();
  [Signal]
  public delegate void FireGunEventHandler();
  [Signal]
  public delegate void ReloadGunEventHandler();

  [Export]
  private RayCast3D _aimCast;

  private bool _reloading = false;

  public int CurrentAmmo { get; private set; }

  public override void _Ready()
  {
    CurrentAmmo = MaxAmmo;
  }

  public override async void _Input(InputEvent @event)
  {
    if (CurrentAmmo > 0 && @event.IsActionPressed("fire") && !_reloading)
    {
      CurrentAmmo -= 1;
      EmitSignal(SignalName.FireGun);

      if (_aimCast.IsColliding())
      {
        EmitSignal(SignalName.OnHit);
        _aimCast.GetCollider().Call("OnHitEvent", DamagePerHit);
      }
    }

    if (CurrentAmmo != MaxAmmo && @event.IsActionPressed("reload"))
    {
      CurrentAmmo = MaxAmmo;
      await Reload();
      EmitSignal(SignalName.ReloadGun);
    }
  }


  private async Task Reload()
  {
    _reloading = true;
    await ToSignal(GetTree().CreateTimer(0.3f), "timeout");
    _reloading = false;

  }
}
