using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.InteropServices;
using AOT;

public class HiveRemotePlayManager : MonoBehaviour {
#if !UNITY_EDITOR && UNITY_STANDALONE_WIN
	

	public delegate void RemotePlayCallbackType(int type, string remotePlayJsonData);
	delegate void RegisterCallbackDelegate(RemotePlayCallbackType cb);

	static RegisterCallbackDelegate registerCallbackDelegate;

	/// <summary>
	/// HMODULE에서 lpProcName에 해당하는 함수 주소를 반환
	/// </summary>
	/// <param name="hModule">로드한 HMODULE 인스턴스</param>
	/// <param name="lpProcName">함수포인터를 가져올 함수 이름</param>
	/// <returns>함수를 찾았으면 해당 함수의 포인터 주소를, 아니면 IntPtr.Zero를 반환</returns>
	[DllImport("kernel32", SetLastError = true)]
	static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);


	private static void LoadPlugin() {
		IntPtr handle = hive.HivePluginDllLoader.Load("RemotePlayDll.dll");

		if (handle == IntPtr.Zero) {
			Debug.LogError($"Failed to load RemotePlayDll.dll. Win32Error={Marshal.GetLastWin32Error()}");
			return;
		}

		var regCallPtr = GetProcAddress(handle, "RegisterCallback");

		if (regCallPtr == IntPtr.Zero) {
			Debug.LogError("Required entry points not found in HIVE_PLUGIN.dll");
			return;
		}

		registerCallbackDelegate = Marshal.GetDelegateForFunctionPointer<RegisterCallbackDelegate>(regCallPtr);
	}

	public static void RegisterCallback(RemotePlayCallbackType callback) {
		if (registerCallbackDelegate == null) {
			LoadPlugin();
		}
		registerCallbackDelegate?.Invoke(callback);
	}
	
	// For example - RemotePlayCallbackType
	// [MonoPInvokeCallback (typeof(RemotePlayCallbackType))]
	// public static void RegisterRemoteCallbackFunction(int type, string remotePlayJsonData)
	// {
	// 	RemoteEventBusCallbackFunction(type, remotePlayJsonData);		
	// }
	
#endif    
}
 