using System;

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

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

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

		private readonly IObservable<long?> _source;

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

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

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

			private long _sum;
		}
	}
}
