/*
 *  nscookie.c
 *  nscookie
 *
 *  Created by Bas Scheffers on 29/06/2005.
 *  Copyright 2005 __MyCompanyName__. All rights reserved.
 *
 */

#include "nscookie.h"
#include "ns.h"

int Ns_ModuleVersion = 1;

int Ns_ModuleInit(char *hServer, char *hModule);

static int Ns_CookieInterpInit(Tcl_Interp *interp, void *context);

static int Ns_SetCookie(ClientData context, Tcl_Interp *interp, int argc, char **argv);
static int Ns_GetCookie(ClientData context, Tcl_Interp *interp, int argc, char **argv);


int
Ns_ModuleInit(char *hServer, char *hModule)
{

    return (Ns_TclInitInterps(hServer, Ns_CookieInterpInit, NULL));

}

static int Ns_CookieInterpInit(Tcl_Interp *interp, void *context)
{
        Tcl_CreateCommand(interp, "ns_cookieset", Ns_SetCookie, NULL, NULL);
        Tcl_CreateCommand(interp, "ns_cookieget", Ns_GetCookie, NULL, NULL);
        return NS_OK;
}

// name, value, path, expires, domain, secure
static int Ns_SetCookie(ClientData context, Tcl_Interp *interp, int argc, char **argv)
{
        Ns_Set *headers;
        Ns_Conn *conn;

        char *cookie;

        int size = 0;

        if (argc < 3) {
                return TCL_ERROR;
        } else {
                size = strlen(argv[1]) + strlen(argv[2]) + 2;

                cookie = Ns_Malloc(size);
                memset(cookie, '\0', size);
                strcat(cookie, argv[1]);
                strcat(cookie, "=");
                strcat(cookie, argv[2]);

                if (argc > 3) {
                        size += strlen(argv[3]) + 7;
                        Ns_Realloc(cookie, size);
                        strcat(cookie, "; path=");
                        strcat(cookie, argv[3]);
                }

                if (argc > 4) {
                        size += strlen(argv[4]) + 10;
                        Ns_Realloc(cookie, size);
                        strcat(cookie, "; expires=");
                        strcat(cookie, argv[4]);
                }

                if (argc > 5) {
                        size += strlen(argv[5]) + 9;
                        Ns_Realloc(cookie, size);
                        strcat(cookie, "; domain=");
                        strcat(cookie, argv[5]);
                }

                if (argc > 6) {
                        size += 8;
                        Ns_Realloc(cookie, size);
                        strcat(cookie, "; secure");
                }

                conn = Ns_TclGetConn(interp);
                headers = Ns_ConnOutputHeaders(conn);

                Ns_Log(Notice, "%s", cookie);
                Ns_SetPut(headers, "Foo", "Bar");
                Ns_SetPut(headers, "Cookie", cookie);
                Ns_Log(Notice, "%s", cookie);
                Ns_Free(cookie);
        }

        return NS_OK;
}

static int Ns_GetCookie(ClientData context, Tcl_Interp *interp, int argc, char **argv)
{
        return NS_OK;
}