using System;

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

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

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

		private readonly IObservable<int> _source;

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

			public override void OnNext(int value)
			{
				checked
				{
					try
					{
						this._sum += unchecked((long)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;
		}
	}
}
