using System;

namespace System.Reactive.Linq.ObservableImpl
{
	internal static class Select<TSource, TResult>
	{
		internal sealed class Selector : Producer<TResult, Select<TSource, TResult>.Selector._>
		{
			public Selector(IObservable<TSource> source, Func<TSource, TResult> selector)
			{
				this._source = source;
				this._selector = selector;
			}

			protected override Select<TSource, TResult>.Selector._ CreateSink(IObserver<TResult> observer)
			{
				return new Select<TSource, TResult>.Selector._(this._selector, observer);
			}

			protected override void Run(Select<TSource, TResult>.Selector._ sink)
			{
				sink.Run(this._source);
			}

			private readonly IObservable<TSource> _source;

			private readonly Func<TSource, TResult> _selector;

			internal sealed class _ : Sink<TSource, TResult>
			{
				public _(Func<TSource, TResult> selector, IObserver<TResult> observer)
					: base(observer)
				{
					this._selector = selector;
				}

				public override void OnNext(TSource value)
				{
					TResult tresult;
					try
					{
						tresult = this._selector(value);
					}
					catch (Exception ex)
					{
						base.ForwardOnError(ex);
						return;
					}
					base.ForwardOnNext(tresult);
				}

				private readonly Func<TSource, TResult> _selector;
			}
		}

		internal sealed class SelectorIndexed : Producer<TResult, Select<TSource, TResult>.SelectorIndexed._>
		{
			public SelectorIndexed(IObservable<TSource> source, Func<TSource, int, TResult> selector)
			{
				this._source = source;
				this._selector = selector;
			}

			protected override Select<TSource, TResult>.SelectorIndexed._ CreateSink(IObserver<TResult> observer)
			{
				return new Select<TSource, TResult>.SelectorIndexed._(this._selector, observer);
			}

			protected override void Run(Select<TSource, TResult>.SelectorIndexed._ sink)
			{
				sink.Run(this._source);
			}

			private readonly IObservable<TSource> _source;

			private readonly Func<TSource, int, TResult> _selector;

			internal sealed class _ : Sink<TSource, TResult>
			{
				public _(Func<TSource, int, TResult> selector, IObserver<TResult> observer)
					: base(observer)
				{
					this._selector = selector;
				}

				public override void OnNext(TSource value)
				{
					TResult tresult;
					try
					{
						Func<TSource, int, TResult> selector = this._selector;
						int index = this._index;
						this._index = checked(index + 1);
						tresult = selector(value, index);
					}
					catch (Exception ex)
					{
						base.ForwardOnError(ex);
						return;
					}
					base.ForwardOnNext(tresult);
				}

				private readonly Func<TSource, int, TResult> _selector;

				private int _index;
			}
		}
	}
}
