#include "postgres.h"
#include "fmgr.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

#include "commands/defrem.h"
#include "tsearch/dicts/spell.h"
#include "tsearch/ts_locale.h"
#include "tsearch/ts_public.h"
#include "tsearch/ts_utils.h"
#include "utils/builtins.h"
#include "utils/memutils.h"



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


PG_FUNCTION_INFO_V1(dintdict_init);
Datum dintdict_init(PG_FUNCTION_ARGS);
Datum
dintdict_init(PG_FUNCTION_ARGS) {
        DictInt 	*d;
        List		*dictoptions = (List *) PG_GETARG_POINTER(0);
        ListCell	*l;

        d = (DictInt *) palloc0(sizeof(DictInt));
        d->maxlen = 6;
        d->rejectlong = false;

        foreach(l, dictoptions)
        {
           DefElem    *defel = (DefElem *) lfirst(l);
           if (pg_strcasecmp(defel->defname, "MAXLEN") == 0) {
                        d->maxlen = atoi( defGetString(defel) );
           } else if ( pg_strcasecmp(defel->defname, "REJECTLONG") == 0 ) {
                        if ( pg_strcasecmp(defGetString(defel), "TRUE") == 0 ) {
                                d->rejectlong=true;
                        } else if ( pg_strcasecmp( defGetString(defel), "FALSE" ) == 0 ) {
                                d->rejectlong=false;
                        } else {
                                elog(ERROR,"Unknown value: %s => %s", defel->defname, defGetString(defel));
                        }
            } else {
                        elog(ERROR,"Unknown option: %s => %s",  defel->defname, defGetString(defel) );
            }
        }

         MemoryContextDeleteChildren(CurrentMemoryContext);
        PG_RETURN_POINTER(d);
 }

PG_FUNCTION_INFO_V1(dintdict_lexize);
Datum dintdict_lexize(PG_FUNCTION_ARGS);
Datum
dintdict_lexize(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);
}
