namespace BigoAds.Scripts.Common
{
    using System;
    using System.Collections.Generic;
    using UnityEngine;
    /// 
    /// The unity thread dispatcher.
    /// 
    [DisallowMultipleComponent]
    internal sealed class BigoDispatcher : MonoBehaviour
    {
        private static bool _instanceCreated;
        // The thread safe task queue.
        private static readonly List PostTasks = new List();
        // The executing buffer.
        private static readonly List Executing = new List();
        static BigoDispatcher()
        {
            CreateInstance();
        }
        /// 
        /// Work thread post a task to the main thread.
        /// 
        public static void PostTask(Action task)
        {
            lock (PostTasks)
            {
                PostTasks.Add(task);
            }
        }
        /// 
        /// Start to run this dispatcher.
        /// 
        [RuntimeInitializeOnLoadMethod]
        private static void CreateInstance()
        {
            if (_instanceCreated || !Application.isPlaying) return;
            var go = new GameObject(
                "BigoDispatcher", typeof(BigoDispatcher));
            DontDestroyOnLoad(go);
            _instanceCreated = true;
        }
        private void OnDestroy()
        {
            lock (PostTasks)
            {
                PostTasks.Clear();
            }
            Executing.Clear();
        }
        private void Update()
        {
            lock (PostTasks)
            {
                if (PostTasks.Count > 0)
                {
                    Executing.AddRange(PostTasks);
                    PostTasks.Clear();
                }
            }
            foreach (var task in Executing)
            {
                try
                {
                    task();
                }
                catch (Exception e)
                {
                    Debug.LogError(e.Message, this);
                }
            }
            Executing.Clear();
        }
    }
}