using System;

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

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

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

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

			private double _sum;

			private long _count;
		}
	}
}
