#include <sys/types.h>
#include <err.h>
#include <kernel/thread.h>
#include <platform.h>
#include <platform/interrupts.h>
#include <platform/timer.h>
#include <platform/armemu.h>
#include "platform_p.h"

static platform_timer_callback t_callback;

status_t platform_set_periodic_timer(platform_timer_callback callback, void *arg, time_t interval)
{
	enter_critical_section();

	t_callback = callback;

	*REG(PIT_CLEAR) = 1;
	*REG(PIT_INTERVAL) = interval;
	*REG(PIT_START_PERIODIC) = 1;

	unmask_interrupt(INT_PIT, NULL);

	exit_critical_section();

	return NO_ERROR;
}

time_t current_time(void)
{
	time_t time;
	*REG(SYSINFO_TIME_LATCH) = 1;
	time = *REG(SYSINFO_TIME_SECS) * 1000;
	time += *REG(SYSINFO_TIME_USECS) / 1000;
			
	return time;
}

static enum handler_return platform_tick(void *arg)
{
	if (t_callback) {
		return t_callback(arg, current_time());
	} else {
		return INT_NO_RESCHEDULE;
	}
}

void platform_init_timer(void)
{
	register_int_handler(INT_PIT, &platform_tick, NULL);
}

