using System;

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

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

			protected override void Run(SingleOrDefaultAsync<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)
				{
					if (this._seenValue)
					{
						base.ForwardOnError(new InvalidOperationException(Strings_Linq.MORE_THAN_ONE_ELEMENT));
						return;
					}
					this._value = value;
					this._seenValue = true;
				}

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

				private TSource _value;

				private bool _seenValue;
			}
		}

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

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

			protected override void Run(SingleOrDefaultAsync<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)
					{
						if (this._seenValue)
						{
							base.ForwardOnError(new InvalidOperationException(Strings_Linq.MORE_THAN_ONE_MATCHING_ELEMENT));
							return;
						}
						this._value = value;
						this._seenValue = true;
					}
				}

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

				private readonly Func<TSource, bool> _predicate;

				private TSource _value;

				private bool _seenValue;
			}
		}
	}
}
