#pragma once
namespace HostServer{
    class SyncTime
    {
    public:
        SyncTime(){}
        SyncTime(unsigned long long upperIdCode, long long receiveTime,bool isRTimeOverflow, long long sendTime, bool isSTimeOverflow, unsigned short syncLevel)
            :_upperIdCode(upperIdCode),
            _receiveTime(receiveTime), _sendTime(sendTime), 
            _syncLevel(syncLevel),
            _timeDelay(0),
            _isRTimeOverflow(isRTimeOverflow), _isSTimeOverflow(isSTimeOverflow)
        {}

        SyncTime(SyncTimeMsg &msg, SyncTimeMsg &upperMsg, SyncTime* s = NULL)
            :_upperIdCode(msg.UpperIdCode()),
            _receiveTime(msg.LocalStationReceiveTime()), _sendTime(upperMsg.LocalStationSendTime()), 
            _syncLevel(msg.SyncLevel()),
            _timeDelay(0)
        {
            // 根据历史记录解决时间戳溢出的问题
            if(s == NULL)
            {
                _isRTimeOverflow = false;
                _isSTimeOverflow = false;
            }
            else
            {
                _isRTimeOverflow = (_receiveTime < s->RealReceiveTime()) ? !s->IsRTimeOverflow() : s->IsRTimeOverflow();
                _isSTimeOverflow = (_sendTime < s->RealSendTime()) ? !s->IsSTimeOverflow() : s->IsSTimeOverflow();

                // 解决同时溢出的问题
                if(_isRTimeOverflow && _isSTimeOverflow)
                {
                    _isRTimeOverflow = false;
                    _isSTimeOverflow = false;
                }
            }
        }

        unsigned long long UpperIdCode() const { return _upperIdCode; }

        unsigned long long ReceiveTime() const 
        { 
            return _receiveTime + (_isRTimeOverflow ? TIME_MAX : 0); 
        }
        unsigned long long RealReceiveTime() const { return _receiveTime; }
        void ReceiveTime(unsigned long long val) { _receiveTime = val; }

        bool IsRTimeOverflow() const { return _isRTimeOverflow; }
        void IsRTimeOverflow(bool val) { _isRTimeOverflow = val; }

        unsigned long long SendTime() const 
        { 
            return _sendTime + (_isSTimeOverflow ? TIME_MAX : 0); 
        }

        unsigned long long RealSendTime() const { return _sendTime; }

        void SendTime(unsigned long long val) { _sendTime = val; }

        bool IsSTimeOverflow() const { return _isSTimeOverflow; }
        void IsSTimeOverflow(bool val) { _isSTimeOverflow = val; }

        unsigned short SyncLevel() const { return _syncLevel; }
        void SyncLevel(unsigned short val) { _syncLevel = val; }

        long long TimeDelay() const { return _timeDelay; }
        void TimeDelay(long long val) { _timeDelay = val; }

        
    private:
        unsigned long long _upperIdCode;
        unsigned long long _receiveTime;
        bool _isRTimeOverflow;
        unsigned long long _sendTime;
        bool _isSTimeOverflow;
        unsigned short _syncLevel;
        long long _timeDelay;
    };   
}
