using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class TakeUntilPredicate<TSource> : Producer<TSource, TakeUntilPredicate<TSource>.TakeUntilPredicateObserver>
	{
		public TakeUntilPredicate(IObservable<TSource> source, Func<TSource, bool> stopPredicate)
		{
			this._source = source;
			this._stopPredicate = stopPredicate;
		}

		protected override TakeUntilPredicate<TSource>.TakeUntilPredicateObserver CreateSink(IObserver<TSource> observer)
		{
			return new TakeUntilPredicate<TSource>.TakeUntilPredicateObserver(observer, this._stopPredicate);
		}

		protected override void Run(TakeUntilPredicate<TSource>.TakeUntilPredicateObserver sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<TSource> _source;

		private readonly Func<TSource, bool> _stopPredicate;

		internal sealed class TakeUntilPredicateObserver : IdentitySink<TSource>
		{
			public TakeUntilPredicateObserver(IObserver<TSource> downstream, Func<TSource, bool> predicate)
				: base(downstream)
			{
				this._stopPredicate = predicate;
			}

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

			public override void OnError(Exception error)
			{
				base.ForwardOnError(error);
			}

			public override void OnNext(TSource value)
			{
				base.ForwardOnNext(value);
				bool flag = false;
				try
				{
					flag = this._stopPredicate(value);
				}
				catch (Exception ex)
				{
					base.ForwardOnError(ex);
					return;
				}
				if (flag)
				{
					base.ForwardOnCompleted();
				}
			}

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