using System;
using System.Collections.Generic;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class OnErrorResumeNext<TSource> : Producer<TSource, OnErrorResumeNext<TSource>._>
	{
		public OnErrorResumeNext(IEnumerable<IObservable<TSource>> sources)
		{
			this._sources = sources;
		}

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

		protected override void Run(OnErrorResumeNext<TSource>._ sink)
		{
			sink.Run(this._sources);
		}

		private readonly IEnumerable<IObservable<TSource>> _sources;

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

			protected override IEnumerable<IObservable<TSource>> Extract(IObservable<TSource> source)
			{
				OnErrorResumeNext<TSource> onErrorResumeNext = source as OnErrorResumeNext<TSource>;
				if (onErrorResumeNext != null)
				{
					return onErrorResumeNext._sources;
				}
				return null;
			}

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

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

			protected override bool Fail(Exception error)
			{
				this.OnError(error);
				return true;
			}
		}
	}
}
