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

 Copyright 2016 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 "GribExaminer.h"

#include <string>

#include <QPixmap>

#include "Metview.h"
#include "MvQApplication.h"
#include "MvQKeyManager.h"
#include "GribMetaData.h"
#include "MvQMethods.h"
#include "DocHighlighter.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);
    }

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

    //Filter
    const char* temporary = (const char*)in("TEMPORARY");
    //const char *offset=in("TEMPORARY");

    //Reading the offset values following the techique
    // used in function  "_request_to_fieldset" in field.c in MARS
    int cnt = in.countValues("OFFSET");
    std::vector<off_t> offset;
    for (int i = 0; i < cnt; i++) {
        const char* cval;
        in.getValue(cval, "OFFSET", i);
#ifdef LARGE_FILES_SUPPORT
        offset.push_back(atoll(cval));
#else
        offset.push_back(atol(cval));
#endif
    }

    cnt = in.countValues("LENGTH");
    std::vector<int> len;
    for (int i = 0; i < cnt; i++) {
        int ival;
        in.getValue(ival, "LENGTH", i);
        len.push_back(ival);
    }

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

    DocHighlighter::init();

    //Create the grib key manager and initialize it
    auto* manager = new MvQKeyManager(MvQKeyManager::GribType);
    manager->loadProfiles();

    //Create the grib metadata object and initialize it
    auto* grib = new GribMetaData;
    grib->setFileName(fgrib);

    if (temporary && strcmp(temporary, "0") == 0 &&
        offset.size() > 0) {
        grib->setFilter(offset, len);
    }

    //Create the grib browser and initialize it
    auto* browser = new GribExaminer();
    browser->setAppIcon("GRIB");
    browser->init(grib, manager, 0);
    browser->show();

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