Weapons/Components/AmmoComponent.cs
/// <summary>
/// Handles ammo, reloading, and ammo consumption for a weapon.
/// </summary>
[Title( "Ammo Component" ), Icon( "inventory_2" )]
public sealed class AmmoComponent : WeaponComponent
{
	[Property, Sync] public int AmmoCount { get; set; }
	[Property] public int DefaultAmmo { get; set; } = 8;
	[Property] public int MaximumAmmo { get; set; } = 8;
	[Property] public float ReloadTime { get; set; } = 0.5f;

	private bool _reloadLock = false;
	private TimeUntil _timeUntilReloaded;

	public bool IsFull => AmmoCount >= MaximumAmmo;

	protected override void OnStart()
	{
		AmmoCount = DefaultAmmo;
	}

	public override void OnGameEvent( string eventName )
	{
		if ( eventName == "shootcomponent.fire" )
			TakeAmmo();
	}

	public void Fill() => AmmoCount = DefaultAmmo;

	public bool HasEnoughAmmo( int amount = 1 ) => AmmoCount >= amount;

	public bool TakeAmmo( int amount = 1 )
	{
		if ( AmmoCount >= amount )
		{
			AmmoCount -= amount;
			return true;
		}
		return false;
	}

	protected override bool CanStart( PlayerPawn player )
	{
		if ( _reloadLock ) return false;
		return Input.Pressed( "Reload" );
	}

	protected override void OnStart( PlayerPawn player )
	{
		base.OnStart( player );

		if ( IsFull ) return;

		_timeUntilReloaded = ReloadTime;
		_reloadLock = true;

		Weapon?.Tags.Set( "reloading", true );
	}

	public override void Simulate()
	{
		base.Simulate();

		if ( _reloadLock && _timeUntilReloaded )
		{
			Weapon?.Tags.Set( "reloading", false );
			Fill();
			_reloadLock = false;
		}
	}
}