using System;
using System.Collections.Generic;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class ToList<TSource> : Producer<IList<TSource>, ToList<TSource>._>
	{
		public ToList(IObservable<TSource> source)
		{
			this._source = source;
		}

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

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

		private readonly IObservable<TSource> _source;

		internal sealed class _ : Sink<TSource, IList<TSource>>
		{
			public _(IObserver<IList<TSource>> observer)
				: base(observer)
			{
				this._list = new List<TSource>();
			}

			public override void OnNext(TSource value)
			{
				this._list.Add(value);
			}

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

			public override void OnCompleted()
			{
				List<TSource> list = this._list;
				this._list = null;
				base.ForwardOnNext(list);
				base.ForwardOnCompleted();
			}

			private List<TSource> _list;
		}
	}
}
