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

namespace EMDHardwareClientSimulation.Connection.RS232
{
    /// <summary>
    /// The RS232Interface class absracts the serial connection
    /// to a ZigBee Device.
    /// </summary>
    public class RS232Interface:iEMDConnection, IDisposable
    {
        #region Class variables
        // ----------------------------------------
        private SerialPort com;
        private RxHandler rxHandler;
        private TxHandler txHandler;

        /// <summary>
        /// EventHandler which signalizes that a new Command
        /// has been received by the RS232Interface.
        /// </summary>
        public event EventHandler<CommandHandler> cmdReceived;
        // ----------------------------------------
        #endregion

        #region Public methods
        // ----------------------------------------
        /// <summary>
        /// Creates a new instance of the class which is
        /// responsible for the communication over RS232
        /// </summary>
        public RS232Interface()
        {            
            Debug.WriteLine("RS232INTERFACE - Instantiated!");
        }
        // ----------------------------------------
        #endregion

        #region iEMDConnection members
        // ----------------------------------------
        /// <summary>
        /// Creates a new connection to a Com port on the computer
        /// </summary>
        /// <returns>bool value which indicates whether the port
        /// could be opened</returns>
        public bool openConnection()
        {
            bool result = false;

            this.com = new SerialPort(Properties.Settings.Default.ComPort, Properties.Settings.Default.BaudRate, Parity.None, Properties.Settings.Default.DataBits, StopBits.One);
            this.com.Encoding = Encoding.ASCII;

            try
            {
                this.com.Open();
                rxHandler = new RxHandler(com);
                txHandler = new TxHandler(com);
                rxHandler.msgReceived += new EventHandler(rxHandler_msgReceived);
                result = true;

                Debug.WriteLine("RS232INTERFACE - RS232 connection opened!");
            }
            catch (Exception e)
            {
                Debug.WriteLine("RS232INTERFACE - Nid gäbig: " + e);
            }

            // add event handler to serial port
            // com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);

            return result;
        }

        /// <summary>
        /// Closes the serial port connection
        /// </summary>
        /// <returns>bool value which indicates whether the port
        /// could be closed</returns>
        public bool closeConnection()
        {
            bool result = false;

            rxHandler.exit();
            txHandler.exit();

            try
            {
                this.com.Close();
                result = true;

                Debug.WriteLine("DEVICEMANAGER - Serial connection closed!");
            }
            catch (Exception e)
            {
                Debug.WriteLine("RS232INTERFACE - Nid gäbig: " + e);
            }

            return result;
        }

        /// <summary>
        /// Sends a command over the RS232 interface
        /// </summary>
        /// <param name="cmd">Command which has to be sent</param>
        public void sendCommand(Command cmd)
        {
            txHandler.addCommand(cmd);

            //Debug.WriteLine("DEVICEMANAGER - Added Command to tx queue!");

#if POWERVALUESIMULATION
            rxHandler.createDummyMessage();
#endif
        }
        // ----------------------------------------
        #endregion

        #region IDisposable Members
        // ----------------------------------------
        /// <summary>
        /// Kei Ahnig was das macht
        /// </summary>
        public void Dispose()
        {
            throw new NotImplementedException();
        }
        // ----------------------------------------
        #endregion 
        
        #region Eventhandler
        // ----------------------------------------
        /// <summary>
        /// Issues an event as soon as a new command message
        /// has been arrived
        /// </summary>
        private void rxHandler_msgReceived(object sender, EventArgs e)
        {
            // call maincontroller
           byte[] msg = rxHandler.getMessage();
            Command cmd = new Command(msg[0], msg[1], new byte[] { msg[2], msg[3], msg[4], msg[5] });
            onCommandReceived(cmd);

            //Debug.WriteLine("RS232INTERFACE - New message received!");
        }

        /// <summary>
        /// Issues an Event tho the EventHandler which handles
        /// newly received Commands
        /// </summary>
        /// <param name="cmdHandler">CommandHandler</param>
        public void onCommandReceived(Command cmd)
        {
            if (this.cmdReceived != null)
            {
                cmdReceived(this, new CommandHandler() { cmd = cmd });
            }
        }
        // ----------------------------------------
        #endregion
    }
}
