using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EMDServer.Common;
using System.Threading;
using System.Diagnostics;
using EMDGui;
using EMDServer.Connection.Visualization;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;

namespace EMDServer.Connection.Visualization
{
    public class VisualizationInterface : iEMDConnection
    {
        #region Class variables
        // ----------------------------------------
        public event EventHandler<CommandHandler> cmdReceived;
        // ----------------------------------------
        #endregion

        #region Public methods
        // ----------------------------------------
        public VisualizationInterface()
        {
        }
        // ----------------------------------------
        #endregion

        #region Private Methods
        // ----------------------------------------
        private RemotingServer server;
        // ----------------------------------------
        #endregion

        #region iEMDConnection members
        // ----------------------------------------
        public bool openConnection()
        {
            this.registerServer();

            return true;
        }

        public bool closeConnection()
        {
            return true;
        }

        public void sendCommand(Command cmd)
        {
            //Debug.WriteLine("VISUALIZATIONINTERFACE - Command sent: ID=" + cmd.Id + ", CMD=" + (Constants.EMD_COMMAND) cmd.Cmd + ", VALUE=" + Util.Utils.getInstance().ConvertByteToDecimal(cmd.Val) );

            if (server != null)
                server.SendDisplay(cmd);            
        }

        public void onCommandReceived(Command cmd)
        {
            //Debug.WriteLine("VISUALIZATIONINTERFACE - Command received: ID=" + cmd.Id + ", CMD=" + (Constants.EMD_COMMAND)cmd.Cmd + ", VALUE=" + cmd.getIntValue());

            if (cmdReceived != null)
                cmdReceived(this, new CommandHandler() { cmd = cmd });
        }
        // ----------------------------------------
        #endregion

        #region privateRemotingIPCMethods
        // ----------------------------------------
        private void registerServer()
        {
            System.Runtime.Remoting.RemotingConfiguration.Configure("IPCServerConfig.xml", false);

            server = new RemotingServer(this);
            RemotingServices.Marshal(server, "server");
        }
        // ----------------------------------------
        #endregion
    }
}
