using System;
using XGame.Framework.Data;
using XGame.Framework.Database;
using XGame.Framework.Memory;
using XGame.Framework.ThreadScheduler;
using XGame.Framework.Time;

namespace XGame.Framework
{
    internal class FrameworkController
    {
        private TimeCorrector _updateCorrector;
        private TimeCorrector _lateUpdateCorrector;

        /// <summary>
        /// 是否已销毁
        /// </summary>
        private Func<bool> _isDestroy;
        /// <summary>
        /// 是否已销毁
        /// </summary>
        private bool IsDestroy => _isDestroy?.Invoke() ?? true;
        public void Init(Func<bool> isDestroy)
        {
            _isDestroy = isDestroy;

            _updateCorrector = new TimeCorrector();
            _lateUpdateCorrector = new TimeCorrector();

            Profiler.BeginSample(this, "ObjectPool.Initialize");
            ObjectPool.Initialize();
            ListPool.Initialize();
            Profiler.EndSample();



            Profiler.BeginSample(this, "XOpencoding.Initialize");
            XOpencoding.Initialize();
            Profiler.EndSample();
        }
        public int Update()
        {
            FrameworkSchedulers.Update();
            if (IsDestroy)
                return 0;
            ThreadSchedulers.Update();
            if (IsDestroy)
                return 0;
            var elapse = _updateCorrector.GetCorrectedTime();
            MainThreadUpdateRegister.Update(elapse);
            return elapse;
        }

        public int LateUpdate()
        {
            var elapse = _lateUpdateCorrector.GetCorrectedTime();
            return elapse;
        }

        public void Dispose()
        {
            _isDestroy = null;
            FrameworkSchedulers.Dispose();
            ThreadSchedulers.Dispose();
            FrameworkEvent.Dispose();
            DataModule.Dispose();
            DatabaseModule.Dispose();
            ListPool.Dispose();
            ObjectPool.Dispose();
            XOpencoding.Dispose();
            MemoryMonitor.Dispose();
        }
    }
}
