using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class AverageDecimal : Producer<decimal, AverageDecimal._>
	{
		public AverageDecimal(IObservable<decimal> source)
		{
			this._source = source;
		}

		protected override AverageDecimal._ CreateSink(IObserver<decimal> observer)
		{
			return new AverageDecimal._(observer);
		}

		protected override void Run(AverageDecimal._ sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<decimal> _source;

		internal sealed class _ : IdentitySink<decimal>
		{
			public _(IObserver<decimal> observer)
				: base(observer)
			{
				this._sum = 0m;
				this._count = 0L;
			}

			public override void OnNext(decimal value)
			{
				checked
				{
					try
					{
						this._sum += value;
						this._count += 1L;
					}
					catch (Exception ex)
					{
						base.ForwardOnError(ex);
					}
				}
			}

			public override void OnCompleted()
			{
				if (this._count > 0L)
				{
					base.ForwardOnNext(this._sum / this._count);
					base.ForwardOnCompleted();
					return;
				}
				base.ForwardOnError(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
			}

			private decimal _sum;

			private long _count;
		}
	}
}
