namespace Component
{
	using SimulationCore;

	/// <summary>
	/// A J-K flip flop is similar to an SR flip flop, but with no invalid/
	/// illegal state. It also has the property that, when both inputs are
	/// active, the output of the gate toggles from one state to the other.
	/// </summary>
	public class JkFlipFlop
	{
		public Pin C { get; } // Clock
		public Pin J { get; }
		public Pin K { get; }
		public Pin Q { get; }
		public Pin Q͂ { get; }

		public JkFlipFlop(Circuit c, PulseDetector pd)
		{
			var q = c.AddNorGate();
			var q͂ = c.AddNorGate();

			var k = c.AddAndGate(3);
			var j = c.AddAndGate(3);

			c.Connect(pd.Out, k.In[2]);
			c.Connect(pd.Out, j.In[0]);

			c.Connect(q.Out, k.In[0], q͂.InputA);
			c.Connect(q͂.Out, j.In[2], q.InputB);

			c.Connect(k.Out, q.InputA);
			c.Connect(j.Out, q͂.InputB);

			this.C = pd.In;
			this.K = k.In[1];
			this.J = j.In[1];
			this.Q = q.Out;
			this.Q͂ = q͂.Out;
		}
	}
}