using System;
using System.Collections.Generic;

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

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

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

		private readonly IObservable<TSource> _source;

		internal sealed class _ : Sink<TSource, TSource[]>
		{
			public _(IObserver<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.OnError(error);
			}

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

			private List<TSource> _list;
		}
	}
}
