/***************************** 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 "MvQEditorListMenu.h"

#include <QDebug>
#include <QString>

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

Editor::~Editor() = default;

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

        // add to the open editor's list menu
        MvQEditorListMenu::add(e);
    }
}

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

const std::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(nullptr);
    }
    current_ = nullptr;
    temporary_ = false;

    // remove from the open editor's list menu
    MvQEditorListMenu::remove(this);
}

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

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

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

void Editor::empty()
{
}


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

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

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