// Copyright (c) OpenMMLab. All rights reserved.

#include <string>
#include <cstdio>

#ifdef _WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#endif

#ifdef _WIN32
#define LIBPREFIX ""
#define LIBSUFFIX ".dll"
#elif defined(__APPLE__)
#define LIBPREFIX "lib"
#define LIBSUFFIX ".dylib"
#else
#define LIBPREFIX "lib"
#define LIBSUFFIX ".so"
#endif

namespace mmdeploy {
namespace {

#ifdef _WIN32
inline static const std::wstring GetDllPath() {
    HMODULE hm = NULL;
    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
      (LPWSTR)&GetDllPath, &hm);
    std::wstring ret;
    ret.resize(MAX_PATH);
    GetModuleFileNameW(hm, &ret[0], ret.size());
    ret = ret.substr(0, ret.find_last_of(L"/\\"));
    return ret;
}
#endif

void* mmdeploy_load_library(const char* name) {
  fprintf(stderr, "loading %s ...\n", name);

#ifdef _WIN32
  auto handle = LoadLibraryExA(name, NULL, LOAD_LIBRARY_SEARCH_USER_DIRS);
  if (handle == NULL) {
    handle = LoadLibraryExA(name, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
  }
#else
  auto handle = dlopen(name, RTLD_NOW | RTLD_GLOBAL);
#endif

  if (!handle) {
    fprintf(stderr, "failed to load library %s\n", name);
    return nullptr;
  }
  return handle;
}

// clang-format off

class Loader {
 public:
  Loader() {
#ifdef _WIN32
    AddDllDirectory(GetDllPath().c_str());
#endif
    const char* modules[] = {
        @_MMDEPLOY_DYNAMIC_MODULES@
    };
    for (const auto name : modules) {
      std::string libname = std::string{} + LIBPREFIX + name + LIBSUFFIX;
      mmdeploy_load_library(libname.c_str());
    }
  }
};

// clang-format on

static Loader loader;

}  // namespace
}  // namespace mmdeploy
