using System;

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

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

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

		private readonly IObservable<long> _source;

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

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

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

			private long _sum;

			private long _count;
		}
	}
}
