using System;

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

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

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

		private readonly IObservable<double?> _source;

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

			public override void OnNext(double? value)
			{
				try
				{
					if (value != null)
					{
						this._sum += value.Value;
						checked
						{
							this._count += 1L;
						}
					}
				}
				catch (Exception ex)
				{
					base.ForwardOnError(ex);
				}
			}

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

			private double _sum;

			private long _count;
		}
	}
}
