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

#include <iostream>
#include "Metview.h"
#include "MvQApplication.h"

#include "MvScanFileType.h"
#include "MvQOdbMetaData.h"
#include "MvQTheme.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 dataPath;

    // Get verb
    std::string verb = in.getVerb();

    marslog(LOG_INFO, "verb=%s", verb.c_str());

    if (verb == "ODB_GEO_POINTS" || verb == "ODB_GEO_VECTORS" ||
        verb == "ODB_XY_POINTS" || verb == "ODB_XY_VECTORS" ||
        verb == "ODB_XY_BINNING") {
        if (const char* path = in("ODB_FILENAME")) {
            dataPath.assign(path);
        }
    }
    else if (const char* path = in("PATH")) {
        dataPath.assign(path);
    }

    if (dataPath.empty()) {
        marslog(LOG_EROR, "No ODB file is specified!");
        exit(1);
    }

    //Find out and check odb format
    std::string odbType = MvOdbType(dataPath.c_str(), true);

    if (odbType != "ODB_NEW" && odbType != "ODB_OLD") {
        marslog(LOG_EROR, "Wrong data type: %s! Only ODB_DB is accepted!", odbType.c_str());
        exit(1);
    }
    else if (odbType == "ODB_NEW") {
#ifndef METVIEW_ODB_NEW
        marslog(LOG_EROR, "Cannot handle ODB-2 data! ODB-2 support is disabled!");
        exit(1);
        return;
#endif
    }
    else if (odbType == "ODB_OLD") {
#ifndef METVIEW_ODB_OLD
        marslog(LOG_EROR, "Cannot handle ODB-1 data! ODB-1 support is disabled!");
        exit(1);
#endif
    }

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

    //Create the oda object and initialize it
    auto* odb = new MvQOdbMetaData(dataPath, odbType);

    //Create the oda examiner and initialize it
    auto* browser = new OdbExaminer;
    browser->setAppIcon("ODB_DB");
    browser->init(odb);
    browser->show();

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