/***************************** 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 <Metview.h>
#include <Cached.h>
#include <sys/types.h>
#include <sys/stat.h>


class DataAccess : public MvService
{
public:
    DataAccess(char* name) :
        MvService(name){};
    void serve(MvRequest&, MvRequest&);
};


void DataAccess::serve(MvRequest& in, MvRequest& out)
{
    printf("entry DataAccess::serve...\n");
    in.print();
    FILE* f;


    Cached pathg = marstmp();
    Cached pathb = marstmp();

    char buf[1024];


    request* r   = in;
    parameter* p = r->params;


    // loop through all the input parameters; we will create a string which
    // we will pass to our script which does the work, formatted like:
    // PARAM1=VALUE1 PARAM2=VALUE2 PARAM3=VALX/VALY/VALZ
    while (p) {
        // 'hidden' parameters start with an underscore - ignore these
        if (*p->name != '_') {
            value* v = p->values;

            sprintf(buf, "%s=", p->name);

            while (v) {
                strcat(buf, v->name);
                if (v->next)
                    strcat(buf, "/");  // a list? separate elements with slashes
                v = v->next;
            }

            char* x = new char[strlen(buf) + 1];
            strcpy(x, buf);
            putenv(x);
        }

        p = p->next;
    }


    sprintf(buf, "$METVIEW_BIN/DataAccessScript %s %s 2>&1",
            (const char*)pathg, (const char*)pathb);

    f = popen(buf, "r");
    if (!f) {
        setError(1, "Cannot execute command %s", buf);
        return;
    }


    while (fgets(buf, sizeof(buf), f)) {
        if (strlen(buf))
            buf[strlen(buf) - 1] = 0;
        sendProgress("%s", buf);
    }

    if (pclose(f) != 0) {
        setError(1, "Script failed");
        return;
    }

    printf("exit DataAccess::serve...\n");


    const char* path = NULL;
    const char* type = NULL;
    int flg          = 0;


    struct stat info;

    if (stat(pathg, &info) == 0 && info.st_size != 0) {
        type = "GRIB";
        path = pathg;
        flg++;
    }

    if (stat(pathb, &info) == 0 && info.st_size != 0) {
        type = "BUFR";
        path = pathb;
        flg++;
    }


    if (flg == 0) {
        setError(1, "No data returned");
        return;
    }

    if (flg != 1) {
        setError(1, "More that one type returned");
        return;
    }

    out              = type;
    out("PATH")      = path;
    out("TEMPORARY") = 1;

    out.print();
    printf("end     ...\n");

    // Clean up

    if (strcmp(path, pathg) != 0)
        unlink(pathg);
    if (strcmp(path, pathb) != 0)
        unlink(pathb);
}

int main(int argc, char** argv)
{
    MvApplication theApp(argc, argv);
    DataAccess data("DATA_ACCESS");

    theApp.run();
}
