using System;

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

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

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

		private readonly IObservable<float> _source;

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

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

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

			private double _sum;

			private long _count;
		}
	}
}
