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

 Copyright 2020 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 "savepool.h"

/*#include <QApplication>
#include <QDebug>

#include "MvQFileDialog.h"*/

#include "MvRequest.h"
#include "MvTmpFile.h"

#include <cctype>
#include <sys/types.h>
#include <sys/stat.h>

#include <unistd.h>
#include "mars.h"

static int gac;
static char** gav;
static svc* gs = nullptr;

static svcid* s_id = nullptr;
static const char* path = nullptr;
static const char* iconName = nullptr;
static char* cptr = nullptr;

void cleanup(const char* file);
void save(svcid* id, request* r, void*);


//=======================================================
// Main part, reused from the original Xt-based version
//=======================================================

void cleanup(const char* file)
{
    if (s_id) {
        if (file) {
            if (cptr && strcmp(cptr, "GRIB") == 0) {
                request* r = empty_request("WRITE");
                set_value(r, "TARGET", "%s", file);
                set_value(r, "FIELDSET", "%s", iconName);
                handle_write(r, nullptr);
                free_all_requests(r);
            }
            else {
                mars_copyfile(path, file);
            }

            set_svc_msg(s_id, "Data from %s saved as %s", iconName, file);
        }
        else {
            set_svc_msg(s_id, "Data from %s not saved", iconName);
        }

        send_reply(s_id, nullptr);

        s_id = nullptr;
        path = nullptr;
        iconName = nullptr;
    }
}

void save(svcid* id, request* r, void*)
{
    if (fork_service(id) > 0)
        return;

    s_id = id;

    const char* verb = request_verb(r);
    if (!verb) {
        set_svc_err(id, 1);
        set_svc_msg(id, "This data cannot be saved");
        return;
    }

    printf("verb=%s\n", verb);

    char* pathStr = nullptr;

    if (strcmp(verb, "ODB_GEO_POINTS") == 0 || strcmp(verb, "ODB_GEO_VECTORS") == 0 ||
        strcmp(verb, "ODB_XY_POINTS") == 0 || strcmp(verb, "ODB_XY_VECTORS") == 0 ||
        strcmp(verb, "ODB_XY_BINNING") == 0) {
        pathStr = (char*)get_value(r, "ODB_FILENAME", 0);
    }
    else {
        pathStr = (char*)get_value(r, "PATH", 0);
        /*iconName  = get_value( r, "_NAME", 0 );
        cptr = r->name;*/
    }

    iconName = get_value(r, "_NAME", 0);
    cptr = r->name;

    printf("icon_name=%s\n", iconName);

    path = pathStr;

    if (!pathStr) {
        printf("no path\n");
        set_svc_err(id, 1);
        set_svc_msg(id, "This data cannot be saved");
        return;
    }

    if (strcmp(cptr, "GRIB") == 0) {
        new_variable(iconName, request_to_fieldset(r), 0);
    }
    if (strcmp(cptr, "PRASTER") == 0) {
        cptr = (char*)get_value(r, "IMPORT_FILE_TYPE", 0);
    }

    // const char* senderAppl = (char*)get_value(r, "_APPL", 0);

    // -----------------------------------------------
    // get the target file name from SavePoolApp
    // -----------------------------------------------

    MvRequest in("ICON");
    in("ICON_NAME") = iconName;

    // the output request will be written into this file
    MvTmpFile outFile(false);
    in("_OUT_REQ_FILE") = outFile.path().c_str();

    // Write request into a file
    MvTmpFile reqFile(false);
    in.save(reqFile.path().c_str(), true);

    // Start the application
    std::string cmd;
    cmd += "$metview_command $METVIEW_BIN/SavePoolApp " +
           reqFile.path() + " $METVIEW_QT_APPLICATION_FLAGS ";

    marslog(LOG_INFO, "Start appliction with command: %s", cmd.c_str());

    system(cmd.c_str());

    MvRequest out;
    out.read(outFile.path().c_str(), false, true);

    std::string targetFile;
    if (const char* ch = out("PATH")) {
        targetFile = std::string(ch);
    }

    // The real save operation
    cleanup(targetFile.empty() ? nullptr : targetFile.c_str());

    exit(0);
}

int main(int argc, char** argv)
{
    marsinit(&argc, argv, nullptr, 0, nullptr);

    gac = argc;
    gav = argv;

    gs = create_service(progname());
    add_service_callback(gs, nullptr, save, nullptr);

    service_run(gs);
}
