#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "cookie.h"
#include "defines.h"
#include "lprintf.h"
#include "lib.h"
#define DMID 14
#include "debug.h"

#define FALSE 0
#define TRUE !FALSE

struct cookie_list {
	char *list[MAX_COOKIES],*raw;
	Wordlist *set;
	int num;
};

Cookies *cookie_init(char *cookies) {
	Cookies *c = calloc(1,sizeof(Cookies));

	if (cookies) {
		c->raw = strdup(cookies);
		c->num = token_split(c->raw,c->list,";=",MAX_COOKIES);
	}
	return c;
}
void cookie_free(Cookies **c) {
	if (!c || !*c) return ;
	if ((*c)->raw) free((*c)->raw);
	free(*c);
	*c = NULL;
}
int cookie_get(Cookies *c, char *name, char *value, int bfsz) {
	int i;

	if (value) value[0] = '\0';
	if (!c) return FALSE;
	for (i = 0; i < c->num; i += 2) {
		if (strcmp(name,c->list[i]) == 0) {
			if (value) ncpy(value,c->list[i+1],bfsz-1);
			return TRUE;
		}
	}	
	return FALSE;
}
void cookie_set(Cookies *c, char *name, char *value, char *domain, char *path, time_t max_age, int secure) {
	char bf[BFSZ],tmp[BFSZ];

	if (!c) return ;
	bf[0] = '\0';
	/* orignal netscape cookie format used this
	if (expires) {
		struct tm *tm;
		
		tm = gmtime(&expires);
		if (tm) strftime(bf,BFSZ,"; expires=%A, %d-%b-%Y %H:%M:%S GMT",tm);
	}
	*/	
	if (domain) {
		lprintf(tmp,BFSZ,"; domain=%s",domain);
		ncat(bf,tmp,BFSZ-1);
	}
	if (path) {
		lprintf(tmp,BFSZ,"; path=%s",path);
		ncat(bf,tmp,BFSZ-1);
	}
	/* rfc specified this instead of expires= */
	if (max_age) {
		lprintf(tmp,BFSZ,"; max-age=%d",(int) max_age);
		ncat(bf,tmp,BFSZ-1);
	}	
	if (secure) {
		ncat(bf,"; secure",BFSZ-1);
	}
	lprintf(tmp,BFSZ,"%s=%s%s",name,value,bf);
	word_add(&c->set,tmp);
}

void cookie_send(Cookies *c, int (*prn)(void *,char *, ...), void *prnp) {
	Wordlist *pc;

	if (!c) return ;
	if (!prn) return ;
	for(pc = c->set; pc; pc = pc->next) {
		prn(prnp, "Set-Cookie: %s\n", pc->word);
	}
}

Wordlist *cookie_list(Cookies *c)
{
	if (c) return c->set;
	return NULL;
}
