#include "zigbeemanager.h"

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

using namespace std;

ZigbeeManager::ZigbeeManager()
{
    if (!loadPlugin()) {
        cout << "Error" << "Could not load the plugin" << endl;
    }
}

bool ZigbeeManager::loadPlugin()
{
    uint i = 0;

    QDir pluginsDir(QCoreApplication::applicationDirPath());
    pluginsDir.cd("plugins");
    const QStringList entries = pluginsDir.entryList(QDir::Files);

    for (const QString &fileName : entries)
    {
        QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
        QObject *plugin = pluginLoader.instance();
        if (plugin)
        {
            zigbeeManagerInterface.insert(i, qobject_cast<ZigbeeManagerInterface *>(plugin));
            if (zigbeeManagerInterface[i])
            {
                zigbeeManagerInterface[i]->initPlugin();
                return true;
            }
            pluginLoader.unload();
        }else
        {
            cout << pluginLoader.errorString().toStdString() << endl;
        }
    }

    return false;
}

