using System;
using XGame.Framework.ThreadScheduler;

namespace XGame.Framework.Time
{
    public class TimeModule : ITimeModule, ITimeUpdate, IDisposable
    {

        private IClock _clock;
        private DateTime _utcStartTime;

        public void Initialize()
        {
            _utcStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            double nowTimestamp = (DateTime.UtcNow - _utcStartTime).TotalMilliseconds;
            _clock = new Clock((long)nowTimestamp);
            MainThreadUpdateRegister.update += Update;
        }

        #region ITimeModule接口实现
        public long GetNowTime(ClockType clockTyp = ClockType.Server)
        {
            return _clock.GetNowTime(clockTyp);
        }

        public void SetTime(long timestamp, ClockType clockTyp = ClockType.Server)
        {
            _clock.SetTime(timestamp, clockTyp);
        }
        public IAlarm AddAlarm(Action action, long triggerTimestamp, ClockType clockTyp = ClockType.Server)
        {
            return _clock.AddAlarm(triggerTimestamp, action, clockTyp);
        }

        public ITimer AddDelayTimer(int delay, Action action)
        {
            return _clock.AddDelayTimer(delay, action);
        }
        public ITimer AddLooperTimer(int interval, Action<int> action, int loopTimes = -1)
        {
            return _clock.AddLooperTimer(interval, interval, action, loopTimes);
        }
        public ITimer AddDelayLooperTimer(int delay, int interval, Action<int> action, int loopTimes = -1)
        {
            return _clock.AddLooperTimer(delay, interval, action, loopTimes);
        }
        #endregion

        #region IUpdate接口实现
        public void Update(int elapse)
        {
            _clock.Update(elapse);
        }
        #endregion

        public void Dispose()
        {
            MainThreadUpdateRegister.update -= Update;
            _clock.Dispose();
            _clock = null;
        }
    }
}