/***************************** 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 <ctype.h>
#include "script.h"

Value Module::Run(const char*, int, Value*)
{
    service_run(Svc);
    return Value();
}

Module::Module(const char* name) :
    Script(name)
{
    Svc = create_service(name);
    add_service_callback(Svc, 0, Serve, this);
    SetRunMode("server");
}

void Module::Serve(svcid* id, request* r, void* t)
{
    auto* m = (Module*)t;
    m->Dispatch(id, r);
}

void Module::Dispatch(svcid* id, request* r)
{
    SvcId = id;
    mars.outproc = PutMessage;

    Value v;
    Value w;

    v.SetContent(r);

    const char* action = get_value(r, "_ACTION", 0);
    /* change to lower ... */
    char* n = NEW_STRING(r->name);
    char* p = n;
    while (*p) {
        if (isupper(*p))
            *p = tolower(*p);
        p++;
    }

    p = strcache(n);
    free(n);


    Function* f = action ? FindHandler(action, 1, &v) : 0;

    if (f == 0)
        f = FindHandler(p, 1, &v);

    if (f == 0) {
        set_svc_err(id, 1);
        set_svc_msg(id, "No handler for %s", p);
        send_reply(id, 0);
    }
    else {
        w = f->Execute(1, &v);
        set_svc_err(id, GetError());
        w.GetValue(r);
        send_reply(id, r);
    }

    SvcId = 0;
    mars.outproc = 0;

    strfree(p);
}
