using CommonNetwork_ICE.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommonNetwork_ICE.Session
{
    /// <summary>
    /// 刷新会话,判断是否会话已经过期
    /// </summary>
    internal class SessionPingThread
    {
        public SessionPingThread(IceClientConnector client, Glacier2.RouterPrx router, long period)
        {
            _client = client;
            _router = router;
            _period = period;
            _done = false;
        }

        public void run()
        {
            _m.Lock();
            try
            {
                while (!_done)
                {
                    try
                    {
                        _router.begin_refreshSession().whenCompleted(
                                                    (Ice.Exception ex) =>
                                                    {
                                                        this.done();
                                                        _client.Close();
                                                    });
                    }
                    catch (Ice.CommunicatorDestroyedException)
                    {
                        //
                        // AMI requests can raise CommunicatorDestroyedException directly.
                        //
                        break;
                    }

                    if (!_done)
                    {
                        _m.TimedWait((int)_period);
                    }
                }
            }
            finally
            {
                _m.Unlock();
            }
        }

        public void done()
        {
            _done = true;
        }

        private IceClientConnector _client;
        private Glacier2.RouterPrx _router;
        private long _period;
        private bool _done = false;
        private readonly IceUtilInternal.Monitor _m = new IceUtilInternal.Monitor();
    }
}