#include "DataSubscribe.h"
#include <QVariant>
#include "LibraryLoader.h"
#include "Publisher.h"
#include <QDebug>
DataSubscribe::DataSubscribe()
{
    //shares = new SharedData();
}

DataSubscribe::~DataSubscribe()
{
    //delete shares;
}


void DataSubscribe::Setup(ModuleInfo &mi)
{
    std::string assemblyName = mi.AssemblyName;
    dataName = mi.Name;
    Publisher* pModule = nullptr;// = (BaseModule)Assembly.LoadFile(Path.GetFullPath(@".\" + assemblyName)).CreateInstance(className);
    pModule = LibraryLoader::load<Publisher>(assemblyName);
    if( pModule == nullptr )
    {
        //        qCritical() << LOG_HEADER << " load " << szPlugin.c_str() << " failed.";
        return;
    }
    if( pModule == nullptr )
    {

        qCritical() << __FILE__ << __LINE__ << " " << assemblyName.c_str() << " load failed.";
        return;
    }

    {
        Publisher* runable = dynamic_cast<Publisher*>(pModule);
        //runable->shares(shares);

        connect(runable, SIGNAL(pubData(const QString& ,const QString& ,const QVariant& )), this, SLOT(OnData(const QString& ,const QString& ,const QVariant&)));
        // ------------- 由于tdengine订阅模块是单例运行,消息发送是广播发送 -------------
        // for(auto it =  dataConsumerList.begin(); it != dataConsumerList.end(); it++){
        //     connect(runable, SIGNAL(pubData(const QString& ,const QString& ,const QVariant& )), *it, SLOT(OnData(const QString& ,const QString& ,const QVariant&)));
        // }
        // ______________
        runable->Run(mi);
    }
}



std::string DataSubscribe::getTypeList()
{
    return "DataStorage::RunnableModule";
}

// void DataSubscribe::setLoader(QLibrary *)
// {

// }

void DataSubscribe::regConsumer(DataConsumer *dc)
{
    dataConsumerList.append(dc);
}

void DataSubscribe::OnData(const QString &user, const QString &key, const QVariant &val)
{
    for(auto it =  dataConsumerList.begin(); it != dataConsumerList.end(); it++){
        if((*it)->dataName == key.toStdString()){
            (*it)->OnData(user, key, val);
        }
    }
}






