/* $Id$ 
 * Tiny reimplementation of time_virt() and time_call_at()
 *
 * Copyright (C) 2008-2009 FAUmachine Team <info@faumachine.org>.
 * This program is free software. You can redistribute it and/or modify it
 * under the terms of the GNU General Public License, either version 2 of
 * the License, or (at your option) any later version. See COPYING.
 */

#include "glue-main.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>

static int failure = 0;
static unsigned long long simulation_time = 0;
static bool terminate = false;

static struct {
	unsigned int n_calls;
	struct {
		void (*func)(void *data);
		void *data;
		unsigned long long tsc;
	} calls[10];
} time_calls;

unsigned long long
fauhdli_time_virt(void)
{
	return simulation_time;
}

void
fauhdli_time_call_at(unsigned long long tsc, void (*func)(void *data), void *data)
{
	assert(time_calls.n_calls < 10);

	time_calls.calls[time_calls.n_calls].func = func;
	time_calls.calls[time_calls.n_calls].data = data;
	time_calls.calls[time_calls.n_calls].tsc = tsc;
	time_calls.n_calls++;
}

int
fauhdli_time_call_delete(void (*func)(void *), void *data)
{
	unsigned int i;
	for (i = 0; i < time_calls.n_calls; i++) {

		if (data == time_calls.calls[i].data) {
			size_t rs = 
				sizeof(time_calls.calls) 
				/ sizeof(time_calls.calls[0])
				- i - 1;

			if (rs == 0) {
				return 0;
			}

			memmove(&time_calls.calls[i], 
				&time_calls.calls[i + 1], 
				rs * sizeof(time_calls.calls[0]));
			return 0;
		}
	}

	return 1;
}

/** enter the main event loop.
 *  May not be called anywhere in the library, as it's not part of
 *  the standard glue-main.
 *  -> only useful in interpreter.c which ships it's own "main"
 */
int
fauhdli_main_event_loop(void)
{
	while (! terminate) {
		unsigned int i;
		int entry = -1;
		unsigned long long min_time = INT64_MAX;

		if (time_calls.n_calls == 0) {
			break;
		}
		
		for (i = 0; i < time_calls.n_calls; i++) {
			if (time_calls.calls[i].tsc <= min_time) {
				min_time = time_calls.calls[i].tsc;
				entry = i;
			}
		}

		assert(entry != -1);
		simulation_time = min_time;
		time_calls.calls[entry].func(time_calls.calls[entry].data);
		
		/* remove entry from queue */
		for (i = entry + 1; i < time_calls.n_calls; i++) {
			time_calls.calls[i - 1].func = 
				time_calls.calls[i].func;
			time_calls.calls[i - 1].data = 
				time_calls.calls[i].data;
			time_calls.calls[i - 1].tsc = time_calls.calls[i].tsc;
		}
		time_calls.n_calls--;
	}

	return failure;
}

void
fauhdli_simulation_quit(int status)
{
	terminate = true;
	failure = status;
}
