using UnityEngine;
using UnityEngine.Rendering;
using XGame.Framework.Asset;

namespace XGame.Framework
{
    internal class Launch : MonoBehaviour
    {
        private bool _isDispose = false;

        private FrameworkController _controller;
        private IGameLogicProxy _gameLogic;

        private void Awake()
        {

        }
        private void Start()
        {
            _controller = new FrameworkController();
            _controller.Init(IsDestroy);
            _gameLogic = GameLogicCreator.Create();
            _gameLogic.Start();
        }
        private int _elapseUpdate = 0;
        private void Update()
        {
            AppManager.FrameCount++;
            try
            {
                var elapse = _controller.Update();
                if (_isDispose)
                    return;
                _elapseUpdate += elapse;
                if (OnDemandRendering.willCurrentFrameRender)
                {
                    _gameLogic?.Update(_elapseUpdate);
                    _elapseUpdate = 0;
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogException(ex);
            }
        }
        private int _elapseLateUpdate = 0;
        private void LateUpdate()
        {
            if (_isDispose) return;
            try
            {
                var elapse = _controller.LateUpdate();
                _elapseLateUpdate += elapse;
                if (OnDemandRendering.willCurrentFrameRender)
                {
                    _gameLogic?.LateUpdate(_elapseLateUpdate);
                    _elapseLateUpdate = 0;
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogException(ex);
            }
        }
        private void OnDestroy()
        {
            Dispose();
        }
        private void OnApplicationQuit()
        {
            try
            {
                Dispose();
                AssetManager.Dispose();
                Log.Dispose();
            }
            catch (System.Exception ex)
            {
                Debug.LogException(ex);
            }
        }

        internal void Dispose()
        {
            if (!_isDispose)
            {
                _isDispose = true;
                _gameLogic?.Dispose();
                _gameLogic = null;
                _controller.Dispose();
                _controller = null;
            }
        }

        private bool IsDestroy()
        {
            return _isDispose;
        }
    }
}
