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

#include <fstream>
#include "fstream_mars_fix.h"

#include "EditorFactory.h"
#include "IconObject.h"
#include "Request.h"
#include "IconClass.h"
#include "Editor.h"
#include "ReplyObserver.h"
#include "MvMiscellaneous.h"
#include "MvTmpFile.h"

#include <cassert>
#include <signal.h>

#define SERVICEEDITOR_MV_DEBUG__

ServiceEditor::ServiceEditor(const IconClass& name, const std::string& kind) :
    Editor(name, kind),
    replyObserver_(nullptr)
{
}

void ServiceEditor::raiseIt()
{
    getRemotePid();

    if (remotePid_ != -1) {
#ifdef SERVICEEDITOR_MV_DEBUG__
        std::cout << "ServiceEditor::raiseIt PID=" << remotePid_ << std::endl;
#endif
        if (isRemoteRunning()) {
            MvRequest r("RAISE_WINDOW");
            r("PID") = remotePid_;
            MvApplication::sendMessage(r);
            // the remote editor app is not running but we have not got the reply
        }
        else {
            // disable the replyobserver
            if (replyObserver_) {
                replyObserver_->editor_ = nullptr;
            }
            // edit again
            edit();
        }
    }
}


void ServiceEditor::closeIt()
{
    editDone();
    // TODO: what else can we do?
}


// -----------------------------------------------------------------
// ServiceEditor::edit
// Called to start editing a macro. We call the macroedit service to
// bring up the Qt macro editor.

void ServiceEditor::edit()
{
    std::string path = current_->path().str();
    assert(replyObserver_ == nullptr);
    assert(remotePid_ == -1);
    assert(pidFile_.empty());

    remotePid_ = -1;
    MvTmpFile pidFile(false);
    pidFile_ = pidFile.path();

    // replyObserver is reference counted so it is safe to create a new object
    replyObserver_ = new ServiceEditorObserver(this, path);
    replyObserver_->start(pidFile_);
}

void ServiceEditor::editDone()
{
    replyObserver_ = nullptr;
    remotePid_ = -1;
    pidFile_.clear();
    Editor::editDone();
}

void ServiceEditor::getRemotePid()
{
    if (!pidFile_.empty() && remotePid_ == -1) {
        std::ifstream f(pidFile_);
        if (f.good()) {
            int pid = 0;
            f >> pid;
            if (metview::isPidValid(pid)) {
                remotePid_ = pid;
                return;
            }
        }
    }
}

bool ServiceEditor::isRemoteRunning() const
{
    if (remotePid_ != -1) {
        return kill(remotePid_, 0) == 0;
    }
    return false;
}

//=================================================================

ServiceEditorObserver::ServiceEditorObserver(ServiceEditor* editor, std::string& path) :
    editor_(editor),
    path_(path)
{
}

void ServiceEditorObserver::start(const std::string& pidFile)
{
    if (!editor_)
        return;

    // Editor::edit will already have set up the path that we need
    std::string kind = editor_->iconClass().name();

    MvRequest r;

    if (kind == "WMSCLIENT") {
        r.read(path_.c_str());
        r("_NAME") = path_.c_str();
        r("_CLASS") = kind.c_str();
    }
    else if (kind == "RTTOV_INPUT_DATA" || kind == "SCM_INPUT_DATA") {
        r = MvRequest(kind.c_str());
        r("PATH") = path_.c_str();
        r("_NAME") = path_.c_str();
        r("_CLASS") = kind.c_str();
    }
    else {
        r = ("MACROEDIT");
        r("PATH") = path_.c_str();                            // path to macro
        r("LANGUAGE") = editor_->iconClass().name().c_str();  // icon class, e.g. MACRO or MAGML
        r("_CLASS") = editor_->iconClass().name().c_str();    // icon class, e.g. MACRO or MAGML
    }

    r("_ACTION") = "edit";
    r("_PID_FILE") = pidFile.c_str();
    r("_WAIT_APP") = "1";
    r.print();

    callService("UiAppManager", r);
}

// the qt editor application finished
void ServiceEditorObserver::reply(const Request& /*r*/, int /*err*/)
{
    if (editor_) {
        editor_->notifyObserverApply();
        editor_->editDone();
    }
}


static EditorMaker<ServiceEditor> maker1("QtMacroEditor");
static EditorMaker<ServiceEditor> maker2("QtOgcClientEditor");
static EditorMaker<ServiceEditor> maker3("QtScmDataEditor");
