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

#include <string>

#include <QtGui>

#include <Metview.h>
#include "MvQService.h"
#include "MvQApplication.h"
#include "MacroEdit.h"
#include "MvQMethods.h"


class MacroEditorApplication;


int main(int argc, char** argv)
{
    if (argc < 2) {
        marslog(LOG_EROR, "No arguments are specified");
        exit(1);
    }

    MvRequest in;
    in.read(argv[1], false, true);

    marslog(LOG_INFO, "Request:");
    in.print();

    if (!in) {
        marslog(LOG_EROR, "No request could be read from request file=%s", argv[1]);
        exit(1);
    }

    MvQApplication::writePidToFile(in);

    // determine the file and the language
    QString language, fileName;
    std::string verb = in.getVerb();

    if (verb == "MACROEDIT") {
        if (const char* cFileName = in("PATH"))
            fileName = QString(cFileName);

        if (const char* cLanguage = in("LANGUAGE"))
            language = QString(cLanguage);
    }
    else {
        if (const char* cFileName = in("PATH")) {
            fileName = QString(cFileName);
        }

        if (verb == "KML")
            language = "MAGML";
        else
            language = "NOTE";
    }

    if (fileName.isEmpty()) {
        marslog(LOG_EROR, "No PATH is specified!");
        exit(1);
    }

    // Create the qt application. The appname must be unique!
    std::string appName = MvApplication::buildAppName("MacroEditor");
    MvQApplication app(argc, argv, appName.c_str(), {"MacroEdit", "window", "editor"});

    // set the application icon
    QPixmap winPix(MvQ::iconPixmapPath(language));
    if (!winPix.isNull()) {
        QApplication::setWindowIcon(QIcon(winPix));
    }
    else {
        winPix = QPixmap(MvQ::iconPixmapPath("MACRO"));
        QApplication::setWindowIcon(QIcon(winPix));
    }

    // create the editor instance itself
    MacroEdit editor("Metview Code Editor");

    editor.loadTextFile(fileName);
    editor.setLanguage(language);
    editor.autoInsertLanguageHeader();
    editor.autoInsertLicence();
    editor.show();

    // register for callbacks from Desktop
    app.registerToDesktop(&editor);

    // enter the Qt event loop
    app.exec();
}
