using System;

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

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

			protected override void Run(LastOrDefaultAsync<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._value = value;
				}

				public override void OnError(Exception error)
				{
					this._value = default(TSource);
					base.ForwardOnError(error);
				}

				public override void OnCompleted()
				{
					TSource value = this._value;
					this._value = default(TSource);
					base.ForwardOnNext(value);
					base.ForwardOnCompleted();
				}

				private TSource _value;
			}
		}

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

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

			protected override void Run(LastOrDefaultAsync<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)
					{
						this._value = default(TSource);
						base.ForwardOnError(ex);
						return;
					}
					if (flag)
					{
						this._value = value;
					}
				}

				public override void OnError(Exception error)
				{
					this._value = default(TSource);
					base.ForwardOnError(error);
				}

				public override void OnCompleted()
				{
					TSource value = this._value;
					this._value = default(TSource);
					base.ForwardOnNext(value);
					base.ForwardOnCompleted();
				}

				private readonly Func<TSource, bool> _predicate;

				private TSource _value;
			}
		}
	}
}
