/***************************** 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 "MvDebugPrintControl.h"
#include "uPlotApp.h"

#include <mars.h>

using namespace std;

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

    // Initialize Mars communication
    marsinit(&argc, argv, 0, 0, 0);
    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;
}

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

    return string(name);
}

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

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

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

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

    // 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, 0);

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

    return app.exec();
}
