using System;

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

			protected override FirstAsync<TSource>.Sequence._ CreateSink(IObserver<TSource> observer)
			{
				return new FirstAsync<TSource>.Sequence._(observer);
			}

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

			private readonly IObservable<TSource> _source;

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

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

				public override void OnCompleted()
				{
					if (!this._found)
					{
						base.ForwardOnError(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
					}
				}

				private bool _found;
			}
		}

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

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

			protected override void Run(FirstAsync<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)
					{
						this._found = true;
						base.ForwardOnNext(value);
						base.ForwardOnCompleted();
					}
				}

				public override void OnCompleted()
				{
					if (!this._found)
					{
						base.ForwardOnError(new InvalidOperationException(Strings_Linq.NO_MATCHING_ELEMENTS));
					}
				}

				private readonly Func<TSource, bool> _predicate;

				private bool _found;
			}
		}
	}
}
