using System;
using System.Collections.Generic;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class ToDictionary<TSource, TKey, TElement> : Producer<IDictionary<TKey, TElement>, ToDictionary<TSource, TKey, TElement>._>
	{
		public ToDictionary(IObservable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
		{
			this._source = source;
			this._keySelector = keySelector;
			this._elementSelector = elementSelector;
			this._comparer = comparer;
		}

		protected override ToDictionary<TSource, TKey, TElement>._ CreateSink(IObserver<IDictionary<TKey, TElement>> observer)
		{
			return new ToDictionary<TSource, TKey, TElement>._(this, observer);
		}

		protected override void Run(ToDictionary<TSource, TKey, TElement>._ sink)
		{
			sink.Run(this._source);
		}

		private readonly IObservable<TSource> _source;

		private readonly Func<TSource, TKey> _keySelector;

		private readonly Func<TSource, TElement> _elementSelector;

		private readonly IEqualityComparer<TKey> _comparer;

		internal sealed class _ : Sink<TSource, IDictionary<TKey, TElement>>
		{
			public _(ToDictionary<TSource, TKey, TElement> parent, IObserver<IDictionary<TKey, TElement>> observer)
				: base(observer)
			{
				this._keySelector = parent._keySelector;
				this._elementSelector = parent._elementSelector;
				this._dictionary = new Dictionary<TKey, TElement>(parent._comparer);
			}

			public override void OnNext(TSource value)
			{
				try
				{
					this._dictionary.Add(this._keySelector(value), this._elementSelector(value));
				}
				catch (Exception ex)
				{
					this._dictionary = null;
					base.ForwardOnError(ex);
				}
			}

			public override void OnError(Exception error)
			{
				this._dictionary = null;
				base.ForwardOnError(error);
			}

			public override void OnCompleted()
			{
				Dictionary<TKey, TElement> dictionary = this._dictionary;
				this._dictionary = null;
				base.ForwardOnNext(dictionary);
				base.ForwardOnCompleted();
			}

			private readonly Func<TSource, TKey> _keySelector;

			private readonly Func<TSource, TElement> _elementSelector;

			private Dictionary<TKey, TElement> _dictionary;
		}
	}
}
