using CommonLang.Log;
using CommonNetwork_ICE.Util;
using CommonServer_ICE.Session;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommonServer_ICE.Server
{
    /// <summary>
    /// TCP网关服务器启动处理
    /// </summary>
    class TcpServerRouter : Ice.Application
    {
        private static Logger log = LoggerFactory.GetLogger("TcpServerRouter");
        // TCP服务器对象
        private IceTcpServer tcpServer;
        private Ice.ObjectAdapter adapter;

        public TcpServerRouter(IceTcpServer tcpServer)
        {
            this.tcpServer = tcpServer;
        }

        /// <summary>
        /// 启动TCP网关接收处理
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public override int run(string[] args)
        {
            try
            {
                adapter = Ice.Application.communicator().createObjectAdapter(Constants.TCP_SERVER_INSTANCE_NAME);
                TcpSessionManager tcpSessionManager = new TcpSessionManager(tcpServer);
                adapter.add(tcpSessionManager, Ice.Application.communicator().stringToIdentity(Constants.TCP_SERVER_SESSION_MANAGER_INSTANCE_NAME));
                adapter.activate();

                log.Info("ICE TCP服务器启动侦听,IP【" + tcpServer.getServerConfig().Ip + "】端口【" + tcpServer.getServerConfig().Port + "】。");
                adapter.getCommunicator().waitForShutdown();
            }
            catch (Exception e)
            {
                Exception innerEx = e.InnerException;
                string msg = "";
                if (innerEx != null)
                {
                    msg = innerEx.Message;
                }
                else
                {
                    msg = e.Message;
                }
                log.Error("ICE服务器启动异常:" + msg);
                return -1;
            }
            return 0;
        }

        /// <summary>
        /// 关闭服务器,释放资源
        /// </summary>
        public void Dispose()
        {
            if (adapter != null)
            {
                adapter.getCommunicator().destroy();
            }
        }
    }
}