using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class Scan<TSource> : Producer<TSource, Scan<TSource>._>
	{
		public Scan(IObservable<TSource> source, Func<TSource, TSource, TSource> accumulator)
		{
			this._source = source;
			this._accumulator = accumulator;
		}

		protected override Scan<TSource>._ CreateSink(IObserver<TSource> observer)
		{
			return new Scan<TSource>._(this._accumulator, observer);
		}

		protected override void Run(Scan<TSource>._ sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<TSource> _source;

		private readonly Func<TSource, TSource, TSource> _accumulator;

		internal sealed class _ : IdentitySink<TSource>
		{
			public _(Func<TSource, TSource, TSource> accumulator, IObserver<TSource> observer)
				: base(observer)
			{
				this._accumulator = accumulator;
			}

			public override void OnNext(TSource value)
			{
				try
				{
					if (this._hasAccumulation)
					{
						this._accumulation = this._accumulator(this._accumulation, value);
					}
					else
					{
						this._accumulation = value;
						this._hasAccumulation = true;
					}
				}
				catch (Exception ex)
				{
					base.ForwardOnError(ex);
					return;
				}
				base.ForwardOnNext(this._accumulation);
			}

			private readonly Func<TSource, TSource, TSource> _accumulator;

			private TSource _accumulation;

			private bool _hasAccumulation;
		}
	}
}
