/**********************************************************************************
* Blueprint Reality Inc. CONFIDENTIAL
* 2019 Blueprint Reality Inc.
* All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains, the property of
* Blueprint Reality Inc. and its suppliers, if any.  The intellectual and
* technical concepts contained herein are proprietary to Blueprint Reality Inc.
* and its suppliers and may be covered by Patents, pending patents, and are
* protected by trade secret or copyright law.
*
* Dissemination of this information or reproduction of this material is strictly
* forbidden unless prior written permission is obtained from Blueprint Reality Inc.
***********************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace BlueprintReality.Utility
{
    public class UnityMainThreadRunner : MonoBehaviour
    {
        private static UnityMainThreadRunner instance;
        private static bool gotDestroyed = false;

        public static void EnsureExists()
        {
            if (instance == null && !gotDestroyed)
            {
                GameObject obj = new GameObject("MainThreadRunner")
                {
                    hideFlags = HideFlags.HideAndDontSave,
                };
                DontDestroyOnLoad(obj);
                instance = obj.AddComponent<UnityMainThreadRunner>();
            }
        }

        public static void RunOnMainThread(Action action)
        {
            EnsureExists();
            instance.EnqueueAction(action);
        }

        private Queue<Action> actions = new Queue<Action>();

        protected void EnqueueAction(Action action)
        {
            lock (actions)
                actions.Enqueue(action);
        }

        private void Update()
        {
            lock (actions)
            {
                while (actions.Count > 0)
                    actions.Dequeue().Invoke();
            }
        }
        private void OnDestroy()
        {
            gotDestroyed = true;
        }
    }
}
