using System;
using System.Collections.Generic;

namespace System.Reactive.Linq.ObservableImpl
{
	internal sealed class ZipObserver<T> : SafeObserver<T>
	{
		public ZipObserver(object gate, IZip parent, int index)
		{
			this._gate = gate;
			this._parent = parent;
			this._index = index;
			this._values = new Queue<T>();
		}

		public Queue<T> Values
		{
			get
			{
				return this._values;
			}
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			if (disposing)
			{
				object gate = this._gate;
				lock (gate)
				{
					this._values.Clear();
				}
			}
		}

		public override void OnNext(T value)
		{
			object gate = this._gate;
			lock (gate)
			{
				this._values.Enqueue(value);
				this._parent.Next(this._index);
			}
		}

		public override void OnError(Exception error)
		{
			base.Dispose();
			object gate = this._gate;
			lock (gate)
			{
				this._parent.Fail(error);
			}
		}

		public override void OnCompleted()
		{
			base.Dispose(true);
			object gate = this._gate;
			lock (gate)
			{
				this._parent.Done(this._index);
			}
		}

		private readonly object _gate;

		private readonly IZip _parent;

		private readonly int _index;

		private readonly Queue<T> _values;
	}
}
