using System;
using System.Collections;

namespace System.Reactive.Linq.ObservableImpl
{
	internal abstract class ZipSink<TResult> : IdentitySink<TResult>, IZip
	{
		protected ZipSink(int arity, IObserver<TResult> observer)
			: base(observer)
		{
			this._gate = new object();
			this._isDone = new bool[arity];
			this._queues = new ICollection[arity];
		}

		public ICollection[] Queues
		{
			get
			{
				return this._queues;
			}
		}

		public void Next(int index)
		{
			bool flag = true;
			ICollection[] queues = this._queues;
			for (int i = 0; i < queues.Length; i++)
			{
				if (queues[i].Count == 0)
				{
					flag = false;
					IL_0026:
					if (flag)
					{
						TResult result;
						try
						{
							result = this.GetResult();
						}
						catch (Exception ex)
						{
							base.ForwardOnError(ex);
							return;
						}
						base.ForwardOnNext(result);
						return;
					}
					bool flag2 = true;
					int j = 0;
					while (j < this._isDone.Length)
					{
						if (j == index || this._isDone[j])
						{
							j++;
						}
						else
						{
							flag2 = false;
							IL_0076:
							if (flag2)
							{
								base.ForwardOnCompleted();
								return;
							}
							return;
						}
					}
					goto IL_0076;
				}
			}
			goto IL_0026;
		}

		protected abstract TResult GetResult();

		public void Fail(Exception error)
		{
			base.ForwardOnError(error);
		}

		public void Done(int index)
		{
			this._isDone[index] = true;
			bool flag = true;
			bool[] isDone = this._isDone;
			for (int i = 0; i < isDone.Length; i++)
			{
				if (!isDone[i])
				{
					flag = false;
					IL_002A:
					if (flag)
					{
						base.ForwardOnCompleted();
					}
					return;
				}
			}
			goto IL_002A;
		}

		protected readonly object _gate;

		private readonly ICollection[] _queues;

		private readonly bool[] _isDone;
	}
}
