using System;

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

			public IObservable<TSource> Combine(Func<TSource, bool> predicate)
			{
				return new Where<TSource>.Predicate(this._source, (TSource x) => this._predicate(x) && predicate(x));
			}

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

			protected override void Run(Where<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;
				}

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

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

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

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

			protected override void Run(Where<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;
				}

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

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

				private int _index;
			}
		}
	}
}
