/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQFeatureFactory.h"

#include <map>

#include "MvQFeatureItem.h"
#include "WsType.h"
#include "WsDecoder.h"

static std::map<std::string, MvQFeatureFactory*>* makers = nullptr;

MvQFeatureFactory::MvQFeatureFactory(const std::string& type)
{
    if (!makers)
        makers = new std::map<std::string, MvQFeatureFactory*>;

    (*makers)[type] = this;
}

MvQFeatureItemPtr MvQFeatureFactory::createInner(WsType* feature)
{
    Q_ASSERT(feature);
    MvQFeatureItemPtr item(nullptr);

    auto type = feature->grItemType().toStdString();
    auto const it = makers->find(type);
    if (it != makers->end()) {
        item = (*it).second->make(feature);
    }

    Q_ASSERT(item);
    return item;
}

MvQFeatureItemPtr MvQFeatureFactory::create(WsType* feature)
{
    Q_ASSERT(feature);
    auto item = createInner(feature);
    Q_ASSERT(item);
    item->init({});
    return item;
}

MvQFeatureItemPtr MvQFeatureFactory::create(const QJsonObject& obj)
{
    QString wsCls, wsType;
    WsDecoder::identify(obj, wsCls, wsType);
    MvQFeatureItemPtr item;
    if (auto feature = WsType::find(wsCls, wsType)) {
        item = MvQFeatureFactory::createInner(feature);
        item->init(obj);
    }
    return item;
}

MvQFeatureItemPtr MvQFeatureFactory::clone(MvQFeatureItemPtr item)
{
    QJsonObject obj;
    item->toJson(obj);
    auto cl = create(obj);
    return cl;
}
