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

#include <iostream>


void perl(request* r)
{
    request* s = r;
    std::cout << "[\n";

    while (s) {
        parameter* p = s->params;
        std::cout << "bless({\n";
        while (p) {
            if (*p->name != '_') {
                std::cout << p->name << " => ";
                value* v = p->values;
                if (v && v->next)
                    std::cout << '[';
                value* w = v;
                int vflg = 0;

                while (w) {
                    if (vflg)
                        std::cout << ',';
                    std::cout << "'" << w->name << "'";
                    vflg++;
                    w = w->next;
                }

                if (v && v->next)
                    std::cout << ']';
                std::cout << ",\n";
            }
            p = p->next;
        }
        std::cout << "}, 'metview::" << s->name << "'),\n";
        s = s->next;
    }
    std::cout << "]\n";
}

void reply(svcid* id, request* r, void* data)
{
    if (r)
        perl(r);
    exit(0);
}

int main(int argc, char** argv)
{
    marsinit(&argc, argv, 0, 0, 0);

    const char* path = (argc > 1) ? argv[1] : "/dev/null";
    const char* mode = (argc > 2) ? argv[2] : "edit";
    const char* req = (argc > 3) ? argv[3] : "/dev/null";

    svc* s = create_service(progname());

    add_reply_callback(s, nullptr, reply, nullptr);

    request* u = read_request_file(req);
    request* r = empty_request("MACRO");
    set_value(r, "PATH", "%s", path);

    if (argc > 3) {
        request* v = empty_request("MACROPARAM");
        set_subrequest(v, "MACRO", r);
        r = v;
        r->next = u;
    }

    set_value(r, "_ACTION", "%s", mode);
    set_value(r, "_NAME", "%s", path);

    call_service(s, "macro", r, 0);
    service_run(s);
}
