// Arguements should be: user_name column, password, group

#include <libpq-fe.h>
#include <string.h>
#include <stdlib.h>

#include "executor/spi.h"       // SPI Module
#include "commands/trigger.h"   // Trigger handler
#include "commands/sequence.h"	// for nextval()

#define CODEBASE		"/root"
#define DROP_USER		"drop_user.pl"
#define CREATE_USER		"create_user.pl"

extern Datum 	generate_history(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(generate_history);

Datum
generate_history(PG_FUNCTION_ARGS)
{
	TriggerData 	*trigdata = (TriggerData *) fcinfo->context;
	TupleDesc	tupdesc;
	Trigger    	*trigger;		/* to get trigger name */
	HeapTuple	rettuple = NULL;
	HeapTuple	storetuple = NULL;
	char	  	**args;			/* arguments */
	int16		nargs;
	Relation	rel;
	char		operation[8];

	int		result;

	/* Used to build query */
	char		*query;

	/* Sequence Name */
	char		seqname[] = "history_tracking_id_seq";

	/* Ensure this is a trigger */
	if (!CALLED_AS_TRIGGER(fcinfo))
		elog(ERROR, "generate_history: not fired by trigger manager");

	/* Determine what needs to be done. */
	if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) {
		rettuple = trigdata->tg_trigtuple;
		storetuple = trigdata->tg_newtuple;
	} else {
		rettuple = trigdata->tg_trigtuple;
		storetuple = trigdata->tg_trigtuple;
	}

	/* Can't allow STATEMENT trigger */
	if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
		elog(ERROR, "generate_history: Cannot handle STATEMENT events");

	/* Get the relation */
	rel = trigdata->tg_relation;
	tupdesc = rel->rd_att;

	trigger = trigdata->tg_trigger;

	/* Ensure there was the right number of arguments */
	nargs = trigger->tgnargs;

	args = trigger->tgargs;

	result = SPI_connect();
	if (result != SPI_OK_CONNECT) {
		elog(ERROR, "generate_history: Died trying to connect");
	}


	/* Setup final insert */
	query = SPI_palloc(200 * sizeof(char));

	sprintf(query, "INSERT INTO history_tracking (\"history_tracking_id\") VALUES ('2')");
	elog(NOTICE, "QUERY: %s", query);


	/* Execute final history INSERT */
	result = SPI_exec(query, 0);
	if (result != SPI_OK_INSERT) {
		elog(ERROR, "Didn't properly Log History");
	}


	/* Clean up and get out */
	elog(NOTICE, "FInish");
	SPI_Finish();

	elog(NOTICE, "Succeeded");

	return PointerGetDatum(rettuple);
}
