/***************************** 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 "uPlotBase.h"
#include "GeoTool.h"
#include "Root.h"
#include "MagPlusInteractiveService.h"
#include "PlotModInteractive.h"
#include "SuperPage.h"

#include "MvQTheme.h"
#include "MvDebugPrintControl.h"
#include "uPlotApp.h"

#include <mars.h>

bool SetUplotEnv(int argc, char** argv, MvRequest& req)
{
    // Create Root instance
    Root::Create();

    // Initialize Mars communication
    marsinit(&argc, argv, nullptr, 0, nullptr);
    mvSetMarslogLevel();

    // Get request to be processed
    if (argc > 1) {
        // Check if the input request exists
        if (access(argv[1], F_OK) == 0) {
            // Read the initial input request saved by uPlotManager
            req.read(argv[1]);
            req.print();
            // Skip UPLOT_MANAGER request
            if (strcmp(req.getVerb(), "GEOTOOL_MANAGER") == 0)
                req.advance();

            return true;
        }
    }

    return false;
}

std::string GetProcessName()
{
    // Build a process name according to the process id
    char name[64];
    sprintf(name, "GeoTool%ld", (long int)getpid());

    return {name};
}

int main(int argc, char** argv)
{
    MvRequest req;

    // Get process name and start GeoTool application
    std::string name = GetProcessName();
    uPlotApp app(argc, argv, name.c_str());

    auto* magplus = new MagPlusInteractiveService();
    MagPlusService::Instance(magplus);

    auto* pm = new PlotModInteractive();
    PlotMod::Instance(pm);

    //---------------------------
    // Load the ui theme
    //---------------------------

    MvQTheme::init(&app);

    // Setup uPlot environment
    if (SetUplotEnv(argc, argv, req)) {
        // Instantiate GeoTool application
        uPlotBase* pw = new GeoTool(req);
        magplus->setPlotApplication(pw);
        SuperPage::setPlotApplication(pw);

        // Initialize plotting dimension
        double x = 14.8;
        double y = 10.5;

        // double x = 29.6;
        // double y = 21;
        pw->setPlotWidgetSize(x, y);

        // Call myself to process the request
        MvRequest req1 = pw->SuperPageRequest();
        MvApplication::callService(name.c_str(), req1, nullptr);

        // Show uPlot
        pw->show();
    }

    return app.exec();
}
