/***************************** 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 "ConfigLoader.h"
//#include "IconClass.h"
//#include "IconInfo.h"
//#include "StandardObject.h"
//#include "stl.h"

using Map = std::multimap<std::pair<std::string, int>, ConfigLoader*>;

static Map* makers = nullptr;

ConfigLoader::ConfigLoader(const std::string& name, int order)
{
    if (makers == nullptr)
        makers = new Map();

    std::pair<std::string, int> p(name, order);
    makers->insert(Map::value_type(p, this));
}

bool ConfigLoader::process(request* r, int order)
{
    std::pair<std::string, int> a(r->name, order);
    std::pair<Map::iterator, Map::iterator> p = makers->equal_range(a);

    for (auto j = p.first; j != p.second; ++j)
        (*j).second->load(r);

    return p.first != p.second;
}

void ConfigLoader::init()
{
    // When calling this function we assume the mars init was already called!

    // Load the whole metview config. All the relevant classes will
    // load their config via ConfigLoader
    int order = 0;
    bool more = true;

    //    marsinit(&argc,argv,0,0,0);
    while (more || order <= 2) {
        more = false;
        request* r = mars.setup;
        while (r) {
            if (ConfigLoader::process(r, order)) {
                more = true;
            }
            r = r->next;
        }
        order++;
    }
}
