#include "VideoPlayerAPI.h"

#include <QApplication>
#include <QLibrary>
#include <qchar.h>
#include <qlibrary.h>

#include "spdlog/spdlog.h"

/* 定义函数 */
using FuncCreateVideoPlayer = IVideoPlayer* (*)();
using FuncDestroyVideoPlayer = void (*)(IVideoPlayer* player);

/* 创建函数指针 */
FuncCreateVideoPlayer pCreateVideoPlayer = nullptr;
FuncDestroyVideoPlayer pDestroyVideoPlayer = nullptr;


/* 加载动态库 */
bool loadVideoPlayerLibrary()
{
    QString libPath = QApplication::applicationDirPath();

#ifdef QT_DEBUG
    libPath += "/libVideoPlayerd"; // Debug版本
#else
    libPath += "/libVideoPlayer"; // Release版本
#endif


#if defined (Q_OS_LINUX)
    libPath += ".so"; // 或者 .dll 或者 .dylib
#elif defined (Q_OS_WIN)
    libPath += ".dll"; // Windows下的动态库
#elif defined (Q_OS_MACOS)
    libPath += ".dylib"; // macOS下的动态库
#endif

    QLibrary lib(libPath);
    if(!lib.load())
    {
        SPDLOG_ERROR("加载VideoPlayerAPI库失败: {}", lib.errorString().toStdString());
        SPDLOG_ERROR("VideoPlayer动态库路径: {}", libPath.toStdString());
        return false;
    }

    pCreateVideoPlayer = reinterpret_cast<FuncCreateVideoPlayer>(lib.resolve("createVideoPlayer"));
    if(!pCreateVideoPlayer)
    {
        SPDLOG_ERROR("无法解析createVideoPlayer函数: {}", lib.errorString().toStdString());
        return false;
    }
    pDestroyVideoPlayer = reinterpret_cast<FuncDestroyVideoPlayer>(lib.resolve("destroyVideoPlayer"));
    if(!pDestroyVideoPlayer)
    {
        SPDLOG_ERROR("无法解析destroyVideoPlayer函数: {}", lib.errorString().toStdString());
        return false;
    }

    return true;
}

/* 创建播放器 */
IVideoPlayer* createPlayer()
{
    if(pCreateVideoPlayer == nullptr)
    {
        SPDLOG_ERROR("createVideoPlayer函数指针为空，请先加载动态库");
        return nullptr;
    }
    return pCreateVideoPlayer();
}

/* 销毁播放器 */
void destroyPlayer(IVideoPlayer* player)
{
    if(pDestroyVideoPlayer == nullptr)
    {
        SPDLOG_ERROR("destroyVideoPlayer函数指针为空，请先加载动态库");
        return;
    }
    pDestroyVideoPlayer(player);
}

