using System;
using System.IO;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Windows.Forms;
using System.Configuration;
using STMes;
using Core.Mes.ServerFrameWork;

namespace Core.Mes.ServerManager
{
    /// <summary>
    /// ClsServerMain 的摘要说明。
    /// </summary>
    public class ClsServerMain : IDisposable
    {
        public ClsServerMain() { }

        public void InitServerMain()
        {
            try
            {
                RemotingGate _rg = new RemotingGate();
                ShowLog("初始化数据库连接......");
                InitDBManager();
                ShowLog("数据库连接初始化完毕！");
                GetServerListDataSet();
                ShowLog("读取应用服务配置......");
                foreach (DataRow dr in this._dsServerList.Tables[0].Rows)
                {
                    LoadAssemblyServer(dr["ServerName"].ToString(), dr["AssemblyName"].ToString(), dr["DBName"].ToString());
                }
            }
            catch (Exception ex)
            {
                ShowLog(ex.Message);
            }
        }

        public delegate void ShowLogDelegate(string log);

        public event ShowLogDelegate ShowLogEvent;

        private void ShowLog(string log)
        {
            if (ShowLogEvent != null)
            {
                ShowLogEvent(log);
            }
        }

        #region "	Property	"
        private Hashtable _dbManagerList = new Hashtable();
        private Hashtable DBManagerList
        {
            set { _dbManagerList = value; }
            get { return _dbManagerList; }
        }
        private Hashtable _htAssemblyServer = new Hashtable();
        private Hashtable HtAssemblyServer
        {
            set { _htAssemblyServer = value; }
            get { return _htAssemblyServer; }
        }
        private DataSet _dsServerList = new DataSet();
        #endregion

        private void InitDBManager()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ShowLog(string.Format("读取配置文件: {0}", config.FilePath));
            string _strDB = config.AppSettings.Settings["MESDB"].Value.ToString();
            string[] strDBs = _strDB.Split('|');

            for (int i = 0; i < strDBs.Length; i++)
            {
                try
                {
                    string str = strDBs[i];
                    DBManagerList.Add(str, new STMes.DBManager(str, "A"));
                    DBManagerList.Add(str + "B", new STMes.DBManager(str, "B"));
                    DBManagerList.Add(str + "C", new STMes.DBManager(str, "C"));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }


        //获得服务端配置信息列表
        private DataTable GetServerConfigInfo()
        {
            return null;
        }
        //==========================================================
        // 加载应用服务
        //==========================================================
        private void LoadAssemblyServer(string serverName, string assName, string dbName)
        {
            try
            {
                Assembly assembly = Assembly.Load(assName);

                IServerPool obj = new IServerPool();
                obj.DBManagerList = DBManagerList;
                obj.ServerName = serverName;
                obj.AssemblyName = assName;

                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsClass && type.IsSubclassOf(typeof(IComponent)))
                    {
                        obj.LoadClass(type, dbName);
                    }
                }

                //== 以服务名键值,加入本地服务列表
                HtAssemblyServer.Add(serverName, obj);

                Dispatcher myDisp = new Dispatcher(obj);
                //Dispatcher myDisp = new Dispatcher();

                RemotingServices.Marshal(myDisp, serverName);

                this.ShowLog("加载" + serverName + "成功！");
            }
            catch (Exception ex)
            {
                this.ShowLog("加载" + serverName + "失败！\n" + ex.Message);
                throw ex;
            }
        }


        private void GetServerListDataSet()
        {
            if (!File.Exists("MesServer.xml"))
            {
                throw new Exception("未找到服务配置文件！");
            }

            _dsServerList.ReadXml("MesServer.xml");

            if (_dsServerList == null || _dsServerList.Tables.Count == 0)
                throw new Exception("配置文件设置错误！");

            _dsServerList.AcceptChanges();

        }
        #region IDisposable 成员

        public void Dispose()
        {
            if (this.DBManagerList != null)
            {
                IEnumerator ie = this.DBManagerList.GetEnumerator();

                while (ie.MoveNext())
                {
                    try
                    {
                        System.Collections.DictionaryEntry id = (System.Collections.DictionaryEntry)ie.Current;

                        STMes.DBManager myDbManager = (STMes.DBManager)id.Value;

                        myDbManager.Dispose();
                        myDbManager = null;
                    }
                    catch { }

                }
                this.DBManagerList.Clear();
            }
            if (STMes.DBManager._dbProxy != null)
            {
                try
                {
                    STMes.DBManager._dbProxy.Dispose();
                }
                catch { }
            }
        }

        #endregion
    }
}
