using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal static class TakeWhile<TSource>
	{
		internal sealed class Predicate : Producer<TSource, TakeWhile<TSource>.Predicate._>
		{
			public Predicate(IObservable<TSource> source, Func<TSource, bool> predicate)
			{
				this._source = source;
				this._predicate = predicate;
			}

			protected override TakeWhile<TSource>.Predicate._ CreateSink(IObserver<TSource> observer)
			{
				return new TakeWhile<TSource>.Predicate._(this._predicate, observer);
			}

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

			private readonly IObservable<TSource> _source;

			private readonly Func<TSource, bool> _predicate;

			internal sealed class _ : IdentitySink<TSource>
			{
				public _(Func<TSource, bool> predicate, IObserver<TSource> observer)
					: base(observer)
				{
					this._predicate = predicate;
					this._running = true;
				}

				public override void OnNext(TSource value)
				{
					if (this._running)
					{
						try
						{
							this._running = this._predicate(value);
						}
						catch (Exception ex)
						{
							base.ForwardOnError(ex);
							return;
						}
						if (this._running)
						{
							base.ForwardOnNext(value);
							return;
						}
						base.ForwardOnCompleted();
					}
				}

				private readonly Func<TSource, bool> _predicate;

				private bool _running;
			}
		}

		internal sealed class PredicateIndexed : Producer<TSource, TakeWhile<TSource>.PredicateIndexed._>
		{
			public PredicateIndexed(IObservable<TSource> source, Func<TSource, int, bool> predicate)
			{
				this._source = source;
				this._predicate = predicate;
			}

			protected override TakeWhile<TSource>.PredicateIndexed._ CreateSink(IObserver<TSource> observer)
			{
				return new TakeWhile<TSource>.PredicateIndexed._(this._predicate, observer);
			}

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

			private readonly IObservable<TSource> _source;

			private readonly Func<TSource, int, bool> _predicate;

			internal sealed class _ : IdentitySink<TSource>
			{
				public _(Func<TSource, int, bool> predicate, IObserver<TSource> observer)
					: base(observer)
				{
					this._predicate = predicate;
					this._running = true;
				}

				public override void OnNext(TSource value)
				{
					if (this._running)
					{
						try
						{
							Func<TSource, int, bool> predicate = this._predicate;
							int index = this._index;
							this._index = checked(index + 1);
							this._running = predicate(value, index);
						}
						catch (Exception ex)
						{
							base.ForwardOnError(ex);
							return;
						}
						if (this._running)
						{
							base.ForwardOnNext(value);
							return;
						}
						base.ForwardOnCompleted();
					}
				}

				private readonly Func<TSource, int, bool> _predicate;

				private bool _running;

				private int _index;
			}
		}
	}
}
