namespace BucketChain;
///
/// Represents a bucket used to transport water.
///
public sealed class Bucket
{
private readonly double _capacityLiters;
private double _contentLiters;
///
/// Creates a new bucket with the given capacity.
///
/// Bucket capacity in liters
public Bucket(double capacityLiters)
{
_capacityLiters = capacityLiters;
_contentLiters = 0D;
}
///
/// Gets if this bucket is currently completely empty or not.
///
public bool IsEmpty => _contentLiters <= 0D;
///
/// Fills the bucket to the brim if enough water is available.
/// If there is not enough water to fill the bucket completely it takes as much as possible.
/// If the bucket is already full no water is taken.
///
/// Max. available water, in liters
/// The amount taken for filling the bucket
public double Fill(double maxAvailable)
{
if (_capacityLiters - _contentLiters <= 0D || maxAvailable <= 0D)
{
return 0D;
}
var amountTaken = _contentLiters;
_contentLiters = _contentLiters + maxAvailable > _capacityLiters
? _capacityLiters
: _contentLiters + maxAvailable;
amountTaken -= _contentLiters;
return Math.Abs(amountTaken);
}
///
/// Empties the bucket. The amount stored within before emptying is returned.
///
/// Amount emptied from the bucket, in liters
public double Empty()
{
var content = _contentLiters;
_contentLiters = 0D;
return content;
}
}