using System.Threading;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace RebootKit.Engine.Foundation {
    public static class EntryPoint {
        private static readonly Logger _logger = new(nameof(EntryPoint));

        private static CancellationTokenSource _cancellationTokenSource;

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
        public static void Start() {
            if (_cancellationTokenSource != null) {
                _cancellationTokenSource.Cancel();
            }

            RR.Shared = null;

            _cancellationTokenSource = new CancellationTokenSource();
            SceneManager.LoadScene(0, LoadSceneMode.Single);

            RunAsync(_cancellationTokenSource.Token).Forget();

#if UNITY_EDITOR
            static void OnPlayerModeState(UnityEditor.PlayModeStateChange state) {
                if (state == UnityEditor.PlayModeStateChange.ExitingPlayMode) {
                    _cancellationTokenSource.Cancel();
                }
            }

            UnityEditor.EditorApplication.playModeStateChanged -= OnPlayerModeState;
            UnityEditor.EditorApplication.playModeStateChanged += OnPlayerModeState;
#endif
        }

        public static async UniTask RunAsync(CancellationToken cancellationToken) {
            using RR instance = new RR();

            RR.Shared = instance;
            
            _logger.Debug("running");

            await instance.Init(cancellationToken);
            await instance.Run(cancellationToken);
            
            _logger.Debug("stopped");
        }
    }
}