/********************************
 *
 * 作者:吴隆健
 * 创建时间: 2019-06-09 10:17:55
 * 
 ********************************/

using MrWu.Debug;
using Server;
using System;
using System.Net;
using System.Threading;
using Server.Core;

namespace GlobalSever.Form
{
    /// <summary>
    /// 服务代理
    /// </summary>
    public abstract class ServerProxy : IServerProxy
    {
        /// <summary>
        /// 程序主窗体
        /// </summary>
        protected ServerForm fm;

        /// <summary>
        /// 标题
        /// </summary>
        public string Title {
            get {
                return ServerName + util;
            }
        }

        /// <summary>
        /// 服务器名称
        /// </summary>
        public string ServerName
        {
            get;
            protected set;
        }

        /// <summary>
        /// 是否自杀
        /// </summary>
        public bool isKill {
            get {
                if (manager == null)
                    return false;
                return manager.isKill;
            }
        }

        /// <summary>
        /// 状态信息
        /// </summary>
        public string status = string.Empty;

        /// <summary>
        /// 是否在运行
        /// </summary>
        public bool IsRun {
            get;
            protected set;
        }
        
        public virtual bool SetThreadSynchronizationContext => true;

        public static ThreadSynchronizationContext _threadSynchronizationContext;

        /// <summary>
        /// 模块单元
        /// </summary>
        public string util {
            get {
                if (manager == null)
                {
                    return string.Empty;
                }
#if DEBUG
                string env = "-Debug-";
#else
                string env = "-Release-";
#endif
                return env + manager.myUtil.id + "-" + manager.myUtil.nodeNum + "-" + manager.myUtil.onlyId + $"-ConfigVersion:{TableManager.VERSION}";
            }
        }

        /// <summary>
        /// 管理器
        /// </summary>
        protected GlobalManager manager {
            get {
                return GlobalManager.instance;
            }
        }

        /// <summary>
        /// 服务器单元工厂
        /// </summary>
        public ServerUtilFactory Factory;

        /// <summary>
        /// 服务器线程
        /// </summary>
        private Thread ServerThread;

        public int GameThreadId
        {
            get
            {
                return ServerThread.ManagedThreadId;
            }
        }

        /// <summary>
        /// 构造器
        /// </summary>
        public ServerProxy()
        {
            Factory = CreateUtilFactory();
            
            GlobalDispatcher.Instance.AddListener(GlobalMsgId.GameNameReadSuccess,OnGameNameReadSuccess);
        }
        
        /// <summary>
        /// 启动服务器
        /// </summary>
        /// <returns></returns>
        public bool Start(ServerForm fm)
        {
            if (!TableManager.Instance.ReadNodeInfo())
            {
                Debug.Error("读取节点信息失败!");
                return false;
            }

            if (!TableManager.Instance.LoadTableData())
            {
                Debug.Error("未找到配置表目录!");
                return false;
            }
            
            Debug.Info("Start ServerProxy");
            
            this.fm = fm;
            if (ServerThread != null)
                return false;
            
            GlobalManager.Factory = Factory;

            manager.OtherConfigInit();
            
            if (!manager.CheckConfig())
            {
                Debug.Error("配置表检查不通过!");
                return false;
            }
            
            if (!manager.Start())
            {
                Debug.Warning("启动失败");
                return false;
            }
            else
            {
                IsRun = true;
                status = "已启动";
                ServerThread = new Thread(Run);
                ServerThread.Start();
                
                #if DEBUG
                uint threadId = ThreadHelper.GetOSThreadId();
                Debug.Info($"ThreadStart MainUI {threadId}");
                #endif
                
                return true;
            }
        }

        private void OnGameNameReadSuccess(object param)
        {
            if (param is string value)
            {
                if (!string.IsNullOrEmpty(value))
                {
                    Debug.Info($"服务器名称:{ServerName}");
                    ServerName = value;
                }
            }
        }

        /// <summary>
        /// 创建工厂
        /// </summary>
        /// <returns></returns>
        protected abstract ServerUtilFactory CreateUtilFactory();
        
        /// <summary>
        /// 循环处理
        /// </summary>
        protected void Run()
        {
            try
            {
                if (SetThreadSynchronizationContext)
                {
                    _threadSynchronizationContext = new ThreadSynchronizationContext();
                    SynchronizationContext.SetSynchronizationContext(_threadSynchronizationContext);
                }
                
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.SystemDefault |
                                                       SecurityProtocolType.Tls | SecurityProtocolType.Tls11 |
                                                       SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

                ServerConst.MainThreadId = Thread.CurrentThread.ManagedThreadId;
                
                Debug.ImportantLog("设置安全协议等级! " + Thread.CurrentThread.ManagedThreadId);
                uint threadId = ThreadHelper.GetOSThreadId();
                Debug.Info($"ThreadStart GameLogic {threadId}");
                
                while (manager.state == ServerState.Runing || manager.state == ServerState.Stoping)
                {
                    if (SetThreadSynchronizationContext)
                    {
                        _threadSynchronizationContext.Update();
                    }
                    
                    manager.Loop();
                    Thread.Sleep(1);
                }
                status = "已停止";
                IsRun = false;
            }
            catch (Exception e)
            {
                Debug.Fatal($"主程序报错 msg:{e.Message},code:{e.StackTrace}");
            }

        }

        /// <summary>
        /// 停止服务器
        /// </summary>
        public virtual void Stop()
        {
            if (manager == null)
                return;
            manager.Quit();
        }

        /// <summary>
        /// 获取服务器自定义面板
        /// </summary>
        public virtual ServerTable[] GetServerTable()
        {
            return new ServerTable[0];
        }

        /// <summary>
        /// 设置是否禁止开战
        /// </summary>
        /// <param name="isNoWar">true 禁止开战，false 可以开战</param>
        public void SetIsCanWar(bool isNoWar)
        {
            manager.IsCanWar = !isNoWar;
            Debug.Info($"设置禁止开战状态:{manager.IsCanWar}");
        }
    }
}
