#include "DataManager.h"
#include "Define.h"
#include "DataManagerProxy.h"
#include "DataSubscribe.h"
#include "DataConsumer.h"
#include <QDebug>

DataManager::DataManager() {

}

DataManager::~DataManager()
{
    /*for(auto it = consumerMap.begin(); it != consumerMap.end(); ++it){
        delete it.value();
    }*/
}

// void DataManager::OnData(std::string key, QVariant val)
// {
//     //consumerMap[key]->OnData(key, val);
// }

void DataManager::Startup(Config& config)
{
    //Config config;
    DataManagerProxy dmp;
    auto lstModules = dmp.loadModuleInfos(config);
    for(auto itModules = lstModules.begin(); itModules != lstModules.end(); itModules++){
        for(auto itr = itModules->consumers.begin(); itr != itModules->consumers.end(); ++itr){
            //ScopedPointer<DataConsumer> consumer {new DataConsumer()};
            DataConsumer * consumer = new DataConsumer();
            ConsumerInfo ci = *itr;
            consumer->Setup(ci);
            consumerMap.insert(QString(itr->SubscribeName.c_str()),consumer);
        }

        for(auto itr = itModules->modules.begin();itr!= itModules->modules.end();++itr)
        {
            ModuleInfo mi = *itr;
            if(consumerMap.contains(itr->Name.c_str())){
                //QScopedPointer<DataSubscribe> subscriber(new DataSubscribe());
                DataSubscribe* subscriber = new DataSubscribe();

                auto mapIt = consumerMap.find(itr->Name.c_str());
                while(mapIt != consumerMap.end() && mapIt.key() == itr->Name.c_str()){
                    subscriber->regConsumer(mapIt.value());
                }
                subscriber->Setup(mi);
                //subscriber->Run();
                subscribers.append(subscriber);
            }
        }
    }

}
