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

 Copyright 2014 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 "Editor.h"
#include "EditorFactory.h"
#include "EditorObserver.h"
#include "Request.h"
#include "IconClass.h"

#include <QDebug>
#include <QString>

Editor::Editor(const IconClass& c,const string& kind):
	class_(c),
	kind_(kind),
	observer_(0),
	current_(0),
	temporary_(false)
{
}

Editor::~Editor()
{
	// Not called

}

void Editor::open(IconObject* icon)
{
	Editor *e = icon->editor();
	if(e == 0) e = EditorFactory::find(icon->editorClass());
	if(e)
	{
	  	e->edit(icon);
	}	
}

const IconClass& Editor::iconClass()
{
	return class_;
}

const string& Editor::kind()
{
	return kind_;
}

void Editor::edit(IconObject* icon)
{
	if(icon != current_)
	{
		temporary_ = false;
		current_ = icon;
		if(current_)  {
			current_->editor(this);
			edit();
			current_->addObserver(this);
		}
	}
	if(current_) 
	{
	  	showIt();
		raiseIt();
	}	
	else
		empty();
}

void Editor::editDone()
{
	if(current_)
	{
	  	current_->removeObserver(this);
	  	current_->editor(0);
	}
	current_ = 0;
}

void Editor::observer(EditorObserver* o)
{
	observer_ = o;
}

void Editor::temporary()
{
	temporary_ = true;
}	

IconObject* Editor::current()
{
	return current_;
}

void Editor::empty()
{
}


string Editor::alternateEditor()
{
	return "NoEditor";
}

void Editor::notifyObserverApply()
{
    if(observer_) {
        observer_->apply(current_);
        observer_ = 0;
    }
}

void Editor::notifyObserverClose()
{
    if(observer_) {
        observer_->close(current_);
        observer_ = 0;
    }
}
