#include <stdio.h>

#include <QDomDocument>
#include <QFile>

#include "LabeledSetFactory.h"

namespace OBJREC
{

LabeledSetFactory::LabeledSetFactory()
{
}

void LabeledSetFactory::createLabeledSetFromXml(std::string sXmlFilename,
                                                       const NICE::Config &p_conf,
                                                       const ClassNames &p_classnames,
                                                       LabeledSet &p_LabelSet)
{

    QDomDocument doc("dummy");
    QFile file(sXmlFilename.c_str());
    if (!file.open(QIODevice::ReadOnly)) {
        std::cout << "Can not open such file" << std::endl;
        return;
    }

    QString errMsg;
    if (!doc.setContent(&file, &errMsg)) {
        std::cout << errMsg.toStdString() << std::endl;
        file.close();
        return;
    }

    file.close();

    /* getting all info */
    QDomElement elements = doc.documentElement();
    QDomDocumentType type= doc.doctype();
    std::string sTypeName = type.name().toStdString();

    //choose appropriate xml-LabeledSet loader according to the documenttype, which had previously been added by ::addCreator
    LabeledSetCreatorInterface *pCreator = this->m_MapLSCreators[ sTypeName ];
    if( pCreator == NULL )
    {
        std::cout << "LabeledSetFactory::createLabeledSetFromXml No creator found for xml type " << sTypeName << std::endl;
        return;
    }

    //call specific loading function for the given xml file.
    pCreator->createLabeledSet( sXmlFilename, p_conf, p_classnames, p_LabelSet );

}

void LabeledSetFactory::addCreator(std::string sCreatorName, LabeledSetCreatorInterface *pCreator)
{
    //is there already a mapper for this document type registered?
    if (this->m_MapLSCreators.find(sCreatorName) != this->m_MapLSCreators.end() )
        return;  //element already exist, so don't try to overwrite it

    // store the mapping
    this->m_MapLSCreators[sCreatorName] = pCreator;
}


}//namespace