using System;

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

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

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

		private readonly IObservable<int?> _source;

		internal sealed class _ : IdentitySink<int?>
		{
			public _(IObserver<int?> observer)
				: base(observer)
			{
			}

			public override void OnNext(int? value)
			{
				checked
				{
					try
					{
						if (value != null)
						{
							this._sum += value.Value;
						}
					}
					catch (Exception ex)
					{
						base.ForwardOnError(ex);
					}
				}
			}

			public override void OnCompleted()
			{
				base.ForwardOnNext(new int?(this._sum));
				base.ForwardOnCompleted();
			}

			private int _sum;
		}
	}
}
