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

#include <iostream>
#include "Metview.h"
#include "MvQService.h"
#include "MvQServiceApplication.h"
#include "MvQKeyManager.h"
#include "BufrMetaData.h"

using namespace std;

// Globals
int ac;
char** av;

class Base : public MvQService
{
protected:
    Base(char* a) :
        MvQService(a){};
};

class MvBufrExaminer : public Base
{
public:
    MvBufrExaminer() :
        Base("BUFR"){};
    void serve(MvRequest&, MvRequest&);
};

void MvBufrExaminer::serve(MvRequest& in, MvRequest& /*out*/)
{
    cout << "--------------MvBufrExaminer::serve()--------------" << endl;
    in.print();

    //Get bufr file name
    const char* tmpc = in("PATH");

    //Set bufr file name
    string fbufr(tmpc);

    //Create the qt application
    MvQServiceApplication app(ac, av);

    //Initialise resorces from a static library (libMvQtGui)
    Q_INIT_RESOURCE(examiner);
    Q_INIT_RESOURCE(keyDialog);
    Q_INIT_RESOURCE(window);
    Q_INIT_RESOURCE(find);

    //Create the bufr key manager and initialize it
    MvQKeyManager* manager = new MvQKeyManager(MvQKeyManager::BufrType);
    manager->loadProfiles();

    //Create the bufr metadata object and initialize it
    BufrMetaData* bufr = new BufrMetaData;
    bufr->setFileName(fbufr);

    //Create the bufr browser and initialize it
    BufrExaminer* browser = new BufrExaminer;
    browser->setAppIcon("BUFR");
    browser->init(bufr, manager, 0);

    browser->show();

    //Listen to the mars event loop!
    setupSocketNotifier();

    // Send message to Desktop (but not to MvExamineManager)
    // to turn the icon green; otherwise, it will stay orange.
    if (strcmp(getenv("METVIEW_MODE"), "examine") != 0) {
        acknowledgeGuiStartup();
    }

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

int main(int argc, char** argv)
{
    ac = argc;
    av = argv;

    MvApplication theApp(argc, argv);

    MvBufrExaminer bufr;

    theApp.run();
}
