using System.Text;
using System.Threading;
using HWModules;
using Microsoft.SPOT;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SWModules;

namespace CPFUnitTests
{
    /// <summary>
    /// -EJM
    /// </summary>
    [TestClass]
    public class UnitTest_ExarFifoProblems
    {
        private HWModules.MotherBoard mb;
        private bool _runonce = false;
        private void Init()
        {
            if (!_runonce)
            {
                mb = HWModules.MotherBoard.Instance;
                _runonce = true;
            }

        }

        private void WaitForLdr0()
        {
            Debug.Print("Press LDR0 Button to Continue... \n");
            while (!mb.Ldr0Pushed)
                Thread.Sleep(100);
            //Clear the state
            mb.Ldr0Pushed = false;
        }

        [TestMethod]
        public void TestI2CSerialPortSlot3A()
        {
            Init();
            Debug.Print("\nI2C UART Slot3A Test // Connect to J3\n");
            //WaitForLdr0();

            mb.Enable12V();mb.Enable5V();
            mb.EnableChannelPower(7);

            var port = new I2CSerialPort("COM7");
            port.DataReceived += port_DataReceived;
            port.Open();

            var msgBytes = Encoding.UTF8.GetBytes("Hello Port 3A\r\n");

            Debug.Print("Transmitting message on port, please type a message back.");

            for (int i=0; i < 10; i++) {
                port.Write(msgBytes, 0, msgBytes.Length);
                Thread.Sleep(1000);
            }

            while (!mb.Ldr0Pushed)
            {
                //port.ProcessHardwareIrq(0,0,DateTime.Now);
                Thread.Sleep(50);
                Debug.Print("BLURGH");
            }
            WaitForLdr0();
            port.Close();
            mb.DisableChannelPower(7);
            mb.Disable12V();
            mb.Disable5V();

        }

        private StringBuilder _sbTemp = new StringBuilder();
        private void port_DataReceived(object sender, EventArgs e)
        {
            var inbuff = new byte[1024];

            var port = (I2CSerialPort) sender;
            port.Read(inbuff, 0, port.BytesToRead);
            _sbTemp.Append(SafeEncoding.GetChars(inbuff));
            Debug.Print("Got Line: " + _sbTemp.ToString());

        }
    
    }
}
