using System;
using System.Threading;
using UnityEngine;

public static class ToponUnityThread
{
    private static readonly object SyncRoot = new object();

    private static SynchronizationContext _unityContext;
    private static int _mainThreadId = -1;

    public static void Initialize()
    {
        if (SynchronizationContext.Current == null)
        {
            return;
        }

        lock (SyncRoot)
        {
            _unityContext = SynchronizationContext.Current;
            _mainThreadId = Thread.CurrentThread.ManagedThreadId;
        }
    }

    public static void Post(Action action)
    {
        if (action == null)
        {
            return;
        }

        var context = _unityContext;
        var currentThreadId = Thread.CurrentThread.ManagedThreadId;
        if (context == null || currentThreadId == _mainThreadId)
        {
            SafeInvoke(action);
            return;
        }

        context.Post(_ => SafeInvoke(action), null);
    }

    private static void SafeInvoke(Action action)
    {
        try
        {
            action();
        }
        catch (Exception exception)
        {
            Debug.LogException(exception);
        }
    }
}
