using System;
using System.Runtime.InteropServices;

namespace PlayPcSdkManaged.Unity.Helpers {

  /// <summary>
  /// Provides a shared, static helper method for handling native-to-managed callback continuations.
  /// </summary>
  internal static class UnityCallbacksHelper {
    /// <summary>
    /// Retrieves the C# continuation delegate from the GCHandle pointer provided by the
    /// native SDK and immediately frees the handle to prevent a memory leak.
    /// </summary>
    /// <typeparam name="T">The type of the delegate to retrieve.</typeparam>
    /// <param name="context">The IntPtr (void*) context passed from the native callback.</param>
    /// <returns>The managed delegate instance, or null if the context was invalid.</returns>
    public static T GetContinuation<T>(IntPtr context)
        where T : class {
      if (context == IntPtr.Zero)
        return null;

      GCHandle handle = GCHandle.FromIntPtr(context);
      try {
        return handle.Target as T;
      } finally {
        if (handle.IsAllocated) {
          handle.Free();
        }
      }
    }
  }
}
