/* 
 * example of dictionary 
 * Teodor Sigaev <teodor@sigaev.ru>
 */
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include "postgres.h"

#include "dict.h"
#include "common.h"

#include "subinclude.h"
#include "ts_locale.h"

 typedef struct {
 	int	maxlen;
 	bool	rejectlong;
 } DictInt;


 PG_FUNCTION_INFO_V1(dinit_intdict);
 Datum dinit_intdict(PG_FUNCTION_ARGS);

 Datum 
 dinit_intdict(PG_FUNCTION_ARGS) {
 	DictInt	*d = (DictInt*)malloc( sizeof(DictInt) );
	Map *cfg, *pcfg;
	text *in;
 
 	if ( !d )
 		elog(ERROR, "No memory");
 	memset(d,0,sizeof(DictInt));
 
 	/* Your INIT code */
/* defaults */
	d->maxlen = 6;
	d->rejectlong = false;

if ( PG_ARGISNULL(0) || PG_GETARG_POINTER(0) == NULL ) { /* no options */
	PG_RETURN_POINTER(d);
}
	in = PG_GETARG_TEXT_P(0);
	parse_cfgdict(in,&cfg);
	PG_FREE_IF_COPY(in, 0);
	pcfg=cfg;

	while (pcfg->key) {
		if ( strcasecmp("MAXLEN", pcfg->key) == 0 ) {
			d->maxlen=atoi(pcfg->value);
		} else if ( strcasecmp("REJECTLONG", pcfg->key) == 0 ) {
			if ( strcasecmp("true", pcfg->value) == 0 ) {
				d->rejectlong=true;
			} else if ( strcasecmp("false", pcfg->value) == 0 ) {
				d->rejectlong=false;
			} else {
				elog(ERROR,"Unknown value: %s => %s", pcfg->key, pcfg->value);
			}
		} else {
			elog(ERROR,"Unknown option: %s => %s", pcfg->key, pcfg->value);
		}
		pfree(pcfg->key);
		pfree(pcfg->value);
		pcfg++;
	}
	pfree(cfg); 	
 
 	PG_RETURN_POINTER(d);
 }

PG_FUNCTION_INFO_V1(dlexize_intdict);
Datum dlexize_intdict(PG_FUNCTION_ARGS);
Datum
dlexize_intdict(PG_FUNCTION_ARGS) {
 	DictInt *d = (DictInt*)PG_GETARG_POINTER(0);
	char       *in = (char*)PG_GETARG_POINTER(1);
 	char *txt = pnstrdup(in, PG_GETARG_INT32(2));
	TSLexeme *res=palloc(sizeof(TSLexeme)*2);

	/* Your INIT dictionary code */
	res[1].lexeme = NULL;
	if  ( PG_GETARG_INT32(2) > d->maxlen ) {
		if ( d->rejectlong ) { 		/* stop, return void array */
			pfree(txt);
			res[0].lexeme = NULL; 
		} else {			/* cut integer */
			txt[d->maxlen] = '\0';			
			res[0].lexeme = txt;
		}
	} else {
		res[0].lexeme = txt;
	}
	
	PG_RETURN_POINTER(res);
}
