#include "load_dc_plugin.h"

#include <QCoreApplication>
#include <QPluginLoader>
#include <QDir>
#include <QDebug>

#include "plugins/interfaces.h"

DCPlugin::DCPlugin()
  : m_hw_interface(0) {
}

DCPlugin::~DCPlugin() {
}

hwinf const *DCPlugin::loadPlugin() {
    QString pluginPath = QCoreApplication::applicationDirPath() + "/plugins/";
    QString pluginFileName = pluginPath + "libCashAgentLib.so";

    QPluginLoader *pluginLoader = new QPluginLoader(pluginFileName);

    if (!pluginLoader->load()) {
        qFatal(pluginLoader->errorString().toStdString().c_str());
    }

    qDebug() <<"loaded plugin: " << pluginLoader->fileName();

    QObject *plugin = pluginLoader->instance();
    if (!plugin) {
        qFatal("cannot load root component of plugin (hwinf ctor failing?");
    }

    // the plugin stays in memory until unloaded by the application
    if ((m_hw_interface = qobject_cast<hwinf *>(plugin)) == nullptr) {
        qFatal("cannot create root component");
    }

    return m_hw_interface;
}
