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

#include <unistd.h>

#include <string>

#include "Metview.h"
#include "MvQApplication.h"
#include "MvQMethods.h"

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


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);
    }


    std::string outPath;
    if (const char* outPathCh = in("_OUT_REQ_FILE")) {
        outPath = std::string(outPathCh);
    }
    else {
        marslog(LOG_EROR, "No output request specified in _OUT_REQ_FILE!");
        exit(1);
    }

    //Get grib file name
    std::string iconName;
    if (const char* tmpc = in("ICON_NAME")) {
        iconName = std::string(tmpc);
    }
    else {
        marslog(LOG_EROR, "No ICON_NAME is specified!");
        exit(1);
    }

    //Find out start directory
    std::string iconDir;
    char* mvDir     = getenv("METVIEW_USER_DIRECTORY");
    const char* buf = mdirname(iconName.c_str());

    if (mvDir && buf) {
        iconDir = std::string(mvDir) + "/" + std::string(buf);
        struct stat iconDirStat;
        if (!(stat(iconDir.c_str(), &iconDirStat) >= 0 && iconDirStat.st_mode & S_IFDIR)) {
            iconDir = std::string();
        }
    }
    if (mvDir && iconDir.empty()) {
        iconDir = std::string(mvDir);
    }

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

    MvQSavePool qSavepool(QString::fromStdString(iconDir));

    //Enter the app loop
    app.exec();

    //Now we have left the qt event loop
    QString fName = qSavepool.selectedFile();

    MvRequest out("SELECTION");
    out("PATH") = fName.toStdString().c_str();
    out.save(outPath.c_str());
}
