﻿using System;
using System.Collections.Concurrent;

namespace RebocapSdk.DemoScenes
{
    public class ThreadUIHelper
    {
        private static ThreadUIHelper _instance;

        public static ThreadUIHelper Instance
        {
            get
            {
                if (_instance == null)
                {
                    // Create a new GameObject with this script
                    _instance = new ThreadUIHelper();
                }

                return _instance;
            }
        }

        private readonly ConcurrentQueue<Action<object[]>> _actions = new();
        private readonly ConcurrentQueue<object[]> _parameters = new();

        // Use this function to add your action to the main thread
        public void RunOnMainThread(Action<object[]> action, params object[] parameter)
        {
            _actions.Enqueue(action);
            _parameters.Enqueue(parameter);
        }

        public void Update()
        {
            // Execute all the actions that were added via RunOnMainThread function
            while (_actions.TryDequeue(out var action) && _parameters.TryDequeue(out var parameter))
            {
                action(parameter);
            }
        }
    }
}