using System;

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

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

		protected override void Run(AverageDecimalNullable._ 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
					{
						if (value != null)
						{
							this._sum += value.Value;
							this._count += 1L;
						}
					}
					catch (Exception ex)
					{
						base.ForwardOnError(ex);
					}
				}
			}

			public override void OnCompleted()
			{
				if (this._count > 0L)
				{
					base.ForwardOnNext(new decimal?(this._sum / this._count));
				}
				else
				{
					base.ForwardOnNext(null);
				}
				base.ForwardOnCompleted();
			}

			private decimal _sum;

			private long _count;
		}
	}
}
