using System;

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

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

			protected override void Run(FirstOrDefaultAsync<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)
				{
					base.ForwardOnNext(value);
					base.ForwardOnCompleted();
				}

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

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

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

			protected override void Run(FirstOrDefaultAsync<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);
						base.ForwardOnCompleted();
					}
				}

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

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