using System;

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

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

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

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

			private double _sum;

			private long _count;
		}
	}
}
