import 'dart:ffi'; // 引入 FFI 库
import 'dart:io' show Platform;

typedef CreateInstanceNative = Pointer<Void> Function();

class TMGLoadDynamic {
  static TMGLoadDynamic _instance = TMGLoadDynamic();
  late DynamicLibrary? gmeSdkLib = null;

  late Pointer<Void> _gmeInstance = CreateInstancePtr();
  late final Pointer<Void> Function() CreateInstancePtr =
      gmeSdkLib!
          .lookup<NativeFunction<CreateInstanceNative>>(
            'GMEUnity_CreateInstance',
          )
          .asFunction<Pointer<Void> Function()>();

  TMGLoadDynamic() {
    if (gmeSdkLib == null) {
      if (Platform.isIOS) {
        gmeSdkLib = DynamicLibrary.process();
      } else if (Platform.isAndroid || Platform.operatingSystem == 'ohos') {
        gmeSdkLib = DynamicLibrary.open("libgmesdk.so");
      } else {
        throw UnsupportedError("Unsupported platform");
      }
    }
  }

  static TMGLoadDynamic GetInstance() {
    if (_instance == null) {
      _instance = TMGLoadDynamic();
    }
    return _instance;
  }

  Pointer<Void> GetGmeSdkInstance() {
    if (_gmeInstance == null) {
      _gmeInstance = CreateInstancePtr();
    }
    return _gmeInstance;
  }

  DynamicLibrary? GetGmeSdkLib() {
    return gmeSdkLib!;
  }
}
