using System;
using System.Collections.Generic;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Runtime.CompilerServices;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class ToObservableLongRunning<TSource> : Producer<TSource, ToObservableLongRunning<TSource>._>
	{
		public ToObservableLongRunning(IEnumerable<TSource> source, ISchedulerLongRunning scheduler)
		{
			this._source = source;
			this._scheduler = scheduler;
		}

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

		protected override void Run(ToObservableLongRunning<TSource>._ sink)
		{
			sink.Run(this._source, this._scheduler);
		}

		private readonly IEnumerable<TSource> _source;

		private readonly ISchedulerLongRunning _scheduler;

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

			public void Run(IEnumerable<TSource> source, ISchedulerLongRunning scheduler)
			{
				IEnumerator<TSource> enumerator = null;
				try
				{
					enumerator = source.GetEnumerator();
				}
				catch (Exception ex)
				{
					base.ForwardOnError(ex);
					return;
				}
				base.SetUpstream(scheduler.ScheduleLongRunning<ValueTuple<ToObservableLongRunning<TSource>._, IEnumerator<TSource>>>(new ValueTuple<ToObservableLongRunning<TSource>._, IEnumerator<TSource>>(this, enumerator), delegate([TupleElementNames(new string[] { "this", "e" })] ValueTuple<ToObservableLongRunning<TSource>._, IEnumerator<TSource>> tuple, ICancelable cancelable)
				{
					tuple.Item1.Loop(tuple.Item2, cancelable);
				}));
			}

			private void Loop(IEnumerator<TSource> enumerator, ICancelable cancel)
			{
				while (!cancel.IsDisposed)
				{
					bool flag = false;
					Exception ex = null;
					TSource tsource = default(TSource);
					try
					{
						if (flag = enumerator.MoveNext())
						{
							tsource = enumerator.Current;
						}
						goto IL_0037;
					}
					catch (Exception ex)
					{
						goto IL_0037;
					}
					IL_002B:
					if (flag)
					{
						base.ForwardOnNext(tsource);
						continue;
					}
					base.ForwardOnCompleted();
					break;
					IL_0037:
					if (ex != null)
					{
						base.ForwardOnError(ex);
						break;
					}
					goto IL_002B;
				}
				enumerator.Dispose();
				base.Dispose();
			}
		}
	}
}
