using System;
using System.Collections.Generic;

namespace System.Reactive.Joins
{
	internal class Plan<T1, T2, T3, T4, T5, T6, TResult> : Plan<TResult>
	{
		internal Pattern<T1, T2, T3, T4, T5, T6> Expression { get; }

		internal Func<T1, T2, T3, T4, T5, T6, TResult> Selector { get; }

		internal Plan(Pattern<T1, T2, T3, T4, T5, T6> expression, Func<T1, T2, T3, T4, T5, T6, TResult> selector)
		{
			this.Expression = expression;
			this.Selector = selector;
		}

		internal override ActivePlan Activate(Dictionary<object, IJoinObserver> externalSubscriptions, IObserver<TResult> observer, Action<ActivePlan> deactivate)
		{
			Action<Exception> action = new Action<Exception>(observer.OnError);
			JoinObserver<T1> firstJoinObserver = Plan<TResult>.CreateObserver<T1>(externalSubscriptions, this.Expression.First, action);
			JoinObserver<T2> secondJoinObserver = Plan<TResult>.CreateObserver<T2>(externalSubscriptions, this.Expression.Second, action);
			JoinObserver<T3> thirdJoinObserver = Plan<TResult>.CreateObserver<T3>(externalSubscriptions, this.Expression.Third, action);
			JoinObserver<T4> fourthJoinObserver = Plan<TResult>.CreateObserver<T4>(externalSubscriptions, this.Expression.Fourth, action);
			JoinObserver<T5> fifthJoinObserver = Plan<TResult>.CreateObserver<T5>(externalSubscriptions, this.Expression.Fifth, action);
			JoinObserver<T6> sixthJoinObserver = Plan<TResult>.CreateObserver<T6>(externalSubscriptions, this.Expression.Sixth, action);
			ActivePlan<T1, T2, T3, T4, T5, T6> activePlan = null;
			activePlan = new ActivePlan<T1, T2, T3, T4, T5, T6>(firstJoinObserver, secondJoinObserver, thirdJoinObserver, fourthJoinObserver, fifthJoinObserver, sixthJoinObserver, delegate(T1 first, T2 second, T3 third, T4 fourth, T5 fifth, T6 sixth)
			{
				TResult tresult;
				try
				{
					tresult = this.Selector(first, second, third, fourth, fifth, sixth);
				}
				catch (Exception ex)
				{
					observer.OnError(ex);
					return;
				}
				observer.OnNext(tresult);
			}, delegate
			{
				firstJoinObserver.RemoveActivePlan(activePlan);
				secondJoinObserver.RemoveActivePlan(activePlan);
				thirdJoinObserver.RemoveActivePlan(activePlan);
				fourthJoinObserver.RemoveActivePlan(activePlan);
				fifthJoinObserver.RemoveActivePlan(activePlan);
				sixthJoinObserver.RemoveActivePlan(activePlan);
				deactivate(activePlan);
			});
			firstJoinObserver.AddActivePlan(activePlan);
			secondJoinObserver.AddActivePlan(activePlan);
			thirdJoinObserver.AddActivePlan(activePlan);
			fourthJoinObserver.AddActivePlan(activePlan);
			fifthJoinObserver.AddActivePlan(activePlan);
			sixthJoinObserver.AddActivePlan(activePlan);
			return activePlan;
		}
	}
}
