using System;

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

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

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

		private readonly IObservable<TSource> _source;

		private readonly T _seed;

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

		internal sealed class _ : Sink<TSource, T>
		{
			public _(Scan<TSource, T> parent, IObserver<T> observer)
				: base(observer)
			{
				this._accumulator = parent._accumulator;
				this._accumulation = parent._seed;
			}

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

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

			private T _accumulation;
		}
	}
}
