/***************************** 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 "EditorFactory.h"
#include "IconClass.h"
#include "Editor.h"
#include "NoEditor.h"

using Map = std::multimap<std::pair<std::string, std::string>, Editor*>;
static Map editors;

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

EditorFactory::EditorFactory(const std::string& name) :
    name_(name)
{
    if (makers == nullptr)
        makers = new std::map<std::string, EditorFactory*>;

    (*makers)[name] = this;
}

EditorFactory::~EditorFactory() = default;

Editor* EditorFactory::find(const IconClass& c)
{
    return find(c, c.editor());
}

Editor* EditorFactory::find(const IconClass& c, const std::string& type)
{
    // Cleaning
    /*for(Map::iterator it = editors.begin(); it != editors.end(); )
    {
        if(it->second->current() == 0)
        {
            std::cout << "Editor deleted:  " <<  it->first.first << " " << it->first.second << std::endl;

            delete it->second;
            editors.erase(it++);
        }
        else
        {
            ++it;
        }
    }*/

    // Find or create
    std::pair<std::string, std::string> name(c.name(), type);
    Editor* e = nullptr;

    std::pair<Map::iterator, Map::iterator> p = editors.equal_range(name);
    for (auto j = p.first; j != p.second; ++j) {
        Editor* editor = (*j).second;
        std::pair<std::string, std::string> n(editor->iconClass().name(), editor->kind());

        if (name == n && editor->current() == nullptr) {
            e = editor;
            break;
        }
    }

    if (e == nullptr) {
        auto j = makers->find(type);
        if (j == makers->end()) {
            e = new NoEditor(c, "NoEditor");
        }
        else
            e = (*j).second->make(c);

        editors.insert(Map::value_type(name, e));
    }

    //    std::cout << "Editors ---------->" << std::endl;
    //    for (Map::iterator it = editors.begin(); it != editors.end(); it++) {
    //        std::cout << " editor: " << it->first.first << " " << it->first.second << std::endl;
    //    }

    return e;
}
