#include <stdio.h>
#include "interact.h"
#include "stringops.h"
#include "socket.h"
#include "group.h"
#include "resp.h"
#include "random_functs.h"

static char output [1024];

typedef struct resp_validated
{
	resp *r;
	struct resp_validated *next;
} resp_validated;

static resp_validated *resp_validated_add (resp_validated *rl, resp *r)
{
	resp_validated *new;

	#ifdef FUNCTIONS
	puts ("**resp_validated_add");
	#endif

	new = allocate (resp_validated);
	new->r = r;
	new->next = rl;
	return new;
}

static void resp_validated_burn (resp_validated *l)
{
	#ifdef FUNCTIONS
	puts ("**resp_validated_burn");
	#endif

	if (l)
	{
		resp_validated_burn (l->next);
		free (l);
	}
}

static resp_validated *resp_validated_valid
	(resp_list *list, int status, int *priority_total)
{
	resp_validated *rl = NULL;
	resp *scan;

	#ifdef FUNCTIONS
	puts ("**resp_validated_valid");
	#endif

	(*priority_total) = 0;

	for (scan = list->head; scan != NULL; scan = scan->next)
	{
		if ((!scan->lowerflag || (scan->lower <= status)) &&
			(!scan->upperflag || (scan->upper >= status)))
		{
			rl = resp_validated_add (rl, scan);
			(*priority_total) += scan->priority;
		}
	}
	return rl;
}

void interact (globals *g, player *p, char *l)
{
	group *gr_scan;
	stim_list *sl_scan;
	resp_validated *rl_list, *rl_scan;
	int result_flag, priority_total;

	#ifdef FUNCTIONS
	puts ("**interact");
	#endif

	for (gr_scan = g->group_list->head;
		gr_scan != NULL; gr_scan = gr_scan->next)
	{
		if (stim_evaluate (gr_scan->s, g->name, l))
		{
			rl_list = resp_validated_valid (gr_scan->r, p->status,
				&priority_total);

			if (rl_list && priority_total)
			{
				priority_total = random_int() % priority_total;

				rl_scan = rl_list;

				do
				{
					priority_total -=
						(rl_scan->r->priority);
					if (priority_total >= 0)
						rl_scan = rl_scan->next;
				}
				while (priority_total >= 0);

				(p->status) += rl_scan->r->status_change;

				resp_parse_output (rl_scan->r->response,
					p->name, g);
			}
			if (rl_list) resp_validated_burn (rl_list);
		}
	}
}