using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.IO.Ports;
using EMDServer.Common;

namespace EMDServer.Connection.RS232
{
    class TxHandler
    {
        #region Class variables
        // ----------------------------------------
        private Queue<Command> txQueue;
        private bool running;
        private SerialPort com;
        // ----------------------------------------
        #endregion

        #region Public methods
        // ----------------------------------------
        /// <summary>
        /// Creates a new instance of the class
        /// </summary>
        /// <param name="com">SerialPort over which data will be sent</param>
        public TxHandler(SerialPort com)
        {
            this.txQueue = new Queue<Command>();
            this.running = true;

            this.com = com;

            // start tx thread
            Thread t = new Thread(new ThreadStart(run));
            t.Start();

            //Debug.WriteLine("TXHANDLER - Instantiated!");
        }

        /// <summary>
        /// Adds a command to the send queue
        /// </summary>
        /// <param name="cmd">Command sent to device</param>
        public void addCommand(Command cmd)
        {
            lock (txQueue)
            {
                txQueue.Enqueue(cmd);                
            }

            //Debug.WriteLine("TXHANDLER - Added output Command to tx queue: ID=" + cmd.Id + ", VALUE=" + cmd.getIntValue());
        }

        /// <summary>
        /// Writes data from the queue to the serial 
        /// port in a separate thread
        /// </summary>
        public void run()
        {
            while (running)
            {
                Command cmd;

                if (txQueue.Count > 0)
                {
                    lock (txQueue)
                    {
                        cmd = txQueue.Dequeue();
                    }

                    try
                    {
                        com.BaseStream.Write(cmd.getOutputCommand(), 0, cmd.getOutputCommand().Length);
                        //Debug.WriteLine("TXHANDLER - Data written: ID=" + cmd.Id + ", CMD=" + (Constants.EMD_COMMAND)cmd.Cmd + ", VALUE=" + cmd.getIntValue());
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("TXHANDLER - Nid gäbig: " + e);
                    }
                }
                else
                {
                    Thread.Sleep(200);
                }
            }
        }

        /// <summary>
        /// stops the sender thread
        /// </summary> 
        public void exit()
        {
            this.running = false;

            //Debug.WriteLine("TXHANDLER - Exit!");
        }
        // ----------------------------------------
        #endregion
    }
}