/***************************** 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"

typedef multimap<pair<string, string>, Editor*> Map;
static Map editors;

static map<string, EditorFactory*>* makers = 0;

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

    (*makers)[name] = this;
}

EditorFactory::~EditorFactory()
{
    // Not called
}

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

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

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

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

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

    if (e == 0) {
        map<string, EditorFactory*>::iterator 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));
    }

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

    return e;
}
