using System;

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

			protected override Any<TSource>.Count._ CreateSink(IObserver<bool> observer)
			{
				return new Any<TSource>.Count._(observer);
			}

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

			private readonly IObservable<TSource> _source;

			internal sealed class _ : Sink<TSource, bool>
			{
				public _(IObserver<bool> observer)
					: base(observer)
				{
				}

				public override void OnNext(TSource value)
				{
					base.ForwardOnNext(true);
					base.ForwardOnCompleted();
				}

				public override void OnCompleted()
				{
					base.ForwardOnNext(false);
					base.ForwardOnCompleted();
				}
			}
		}

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

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

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

			private readonly IObservable<TSource> _source;

			private readonly Func<TSource, bool> _predicate;

			internal sealed class _ : Sink<TSource, bool>
			{
				public _(Func<TSource, bool> predicate, IObserver<bool> 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(true);
						base.ForwardOnCompleted();
					}
				}

				public override void OnCompleted()
				{
					base.ForwardOnNext(false);
					base.ForwardOnCompleted();
				}

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