//	Spludlow Software
//	Copyright © Samuel P. Ludlow 2020 All Rights Reserved
//	Distributed under the terms of the GNU General Public License version 3
//	Distributed WITHOUT ANY WARRANTY; without implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
//	https://www.spludlow.co.uk/LICENCE.TXT
//	The Spludlow logo is a registered trademark of Samuel P. Ludlow and may not be used without permission
//	v1.14

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Spludlow.Io
{
	/// <summary>
	/// Never finished this project
	/// Was building MUX to get more outputs out of parallel port
	/// Had part of this 11 to 64 MUX working on breadboard then got bored
	/// http://www.seattlerobotics.org/encoder/200311/dickens/Multiplexing%20Atricle.html
	/// Might finish one day
	/// </summary>
	public class ParallelPortMux
	{
		private int Address;

		private static int[] GrayCodes = { 0x00, 0x01, 0x03, 0x02, 0x06, 0x07, 0x05, 0x04 };

		private int Size = 8;

		private int[] Datas;    //	could write driect

		public ParallelPortMux()
		{
			this.Address = 0xD050;
			this.Datas = new int[Size];

			this.Push();
			this.Push();
		}

		public ParallelPortMux(int address)
		{
			this.Address = address;
			this.Datas = new int[Size];

			this.Push();
			this.Push();
		}

		public void Set(int index, int data)
		{
			this.Datas[index] = data;
		}

		public void Set(int[] datas)
		{
			for (int index = 0; index < this.Size; ++index)
				this.Datas[index] = datas[index];
		}

		public void Push()
		{
			this.Push(0);
		}

		public void Push(int milliseconds)
		{
			for (int index = 0; index < this.Size; ++index)
			{
				Spludlow.Io.ParallelPort.WriteData(this.Address, this.Datas[index]);
				Spludlow.Io.ParallelPort.WriteControl(this.Address, GrayCodes[index]);

				if (milliseconds > 0)
					System.Threading.Thread.Sleep(milliseconds);
			}
		}

		private int CodeDecimal(string input)
		{
			if (input.Length != 2)
				throw new ApplicationException("Excpected 2 char input:\t" + input);

			return Int32.Parse(input.Substring(0, 1)) << 0 | (Int32.Parse(input.Substring(1, 1)) << 4);
		}

		public void Test(int milliseconds)
		{
			int index = 0;

			while (true)
			{
				DateTime now = DateTime.Now;

				string message = now.ToString("yyyyMMdd0000HHmm0000");  //ss");

				this.Datas[1] = CodeDecimal(message.Substring(index, 2));
				this.Datas[2] = CodeDecimal(now.ToString("ss"));

				this.Push(milliseconds);

				index += 2;
				if (index >= message.Length)
					index = 0;
			}
		}
	}
}