using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Configuration;
using System.Runtime.Serialization.Formatters;
using Core.Mes.ServerFrameWork;
using System.Runtime.Remoting.Lifetime;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Runtime.Remoting.Channels.Http;

namespace Core.Mes.ServerManager
{

    public class RemotingGate
    {

        public RemotingGate()
        {
            StartServer();
        }

        private void StartServer()
        {
            try
            {
                //tcp 端口 默认端口上面 加减10  2次 申请5端口。
                RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;




                #region 主进程端口

                string strPort = System.Configuration.ConfigurationManager.AppSettings["ServerPort"];
                int port = Convert.ToInt32(strPort);

                string strBackupServerPort = System.Configuration.ConfigurationManager.AppSettings["BackupServerPort"];
                int iBackupServerPort = Convert.ToInt32(strBackupServerPort);

                if (TcpListening("127.0.0.1", port) == false)
                {
                    #region 主进程

                    IDictionary props = new Hashtable();
                    props["port"] = port;
                    props["name"] = "corebpm.A";
                    props["timeout"] = 5000;


                    TcpChannel channel = new TcpChannel(props, null, null);
                    ChannelServices.RegisterChannel(channel, false);

                    props = new Hashtable();
                    props["port"] = port + 10;
                    props["name"] = "corebpm.B";
                    props["timeout"] = 5000;
                    channel = new TcpChannel(props, null, null);
                    ChannelServices.RegisterChannel(channel, false);

                    props = new Hashtable();
                    props["port"] = port + 20;
                    props["name"] = "corebpm.C";
                    props["timeout"] = 5000;
                    channel = new TcpChannel(props, null, null);
                    ChannelServices.RegisterChannel(channel, false);


                    props = new Hashtable();
                    props["port"] = port - 10;
                    props["name"] = "corebpm.D";
                    props["timeout"] = 5000;
                    channel = new TcpChannel(props, null, null);
                    ChannelServices.RegisterChannel(channel, false);


                    props = new Hashtable();
                    props["port"] = port - 20;
                    props["name"] = "corebpm.E";
                    props["timeout"] = 5000;
                    channel = new TcpChannel(props, null, null);
                    ChannelServices.RegisterChannel(channel, false);

                    #endregion

                    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    configuration.AppSettings.Settings["MainProcessId"].Value = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
                    configuration.Save();


                }
                else if (TcpListening("127.0.0.1", iBackupServerPort) == false)
                {

                    IDictionary props = new Hashtable();
                    props["port"] = iBackupServerPort;
                    props["name"] = "corebpm.Backup";
                    props["timeout"] = 5000;

                    TcpChannel channel = new TcpChannel(props, null, null);
                    ChannelServices.RegisterChannel(channel, false);

                    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    configuration.AppSettings.Settings["ChildProcessId"].Value = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
                    configuration.Save();
                }
                else
                {
                    WriteLog();
                    //MessageBox.Show("应用服务不需要再开启，确定后退出！");
                    Application.Exit();
                    Process.GetCurrentProcess().Kill();
                }
                #endregion
                //ChannelServices.RegisterChannel(new TcpChannel(Convert.ToInt32(props["port"] )), false);
            }
            catch (Exception ex)
            {
                WriteLog();
                Process.GetCurrentProcess().Kill();
                throw new Exception(ex.Message);
            }
        }
        private void WriteLog()
        {
            string str = Program.isMainProcess == true ? "主进程" : "子进程";
            string path = string.Format(@"{0}/log/Application/{1}.txt", Application.StartupPath, System.DateTime.Now.ToString("yyyy_MM_dd"));

            using (StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8))
            {

                StringBuilder sbtxt = new StringBuilder();
                sbtxt.AppendLine("==============================================");
                sbtxt.AppendLine(string.Format("{1}服务服务加载发生异常退出:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), str));
                sbtxt.AppendLine("==============================================");
                sw.WriteLine(sbtxt.ToString());

            }
        }
        public bool TcpListening(string host, int por)
        {
            TcpClient tc = new TcpClient();
            tc.SendTimeout = tc.ReceiveTimeout = 2000;
            bool value = false;
            try
            {
                tc.Connect(host, por);
                if (tc.Connected)
                {
                    value = true;

                }
            }
            catch
            {
                value = false;
            }
            return value;
        }


    }


}

