#include <stdio.h>
#include <sys/time.h>
#include "xassert.h"
#include "xatexit.h"
#include "xsignal.h"
#include "xrand.h"
#include "timer.h"
#include "opts.h"
#include "port.h"

extern int blink_interval;
extern int cur_state;
extern int ticks_bright;
extern int ticks_dark;

int ticks_max = 0;

void timer_handler (void)
{
	static int ticks_cur = 0;
	char val = 1;

	if (cur_state != STATE_AUTO)
		return;

	if (ticks_max) {
		val = ticks_cur < ticks_bright ? 1 : 0;
		ticks_cur++;
		ticks_cur %= ticks_max;
	}

	port_set (val ? xrand() % 7 + 1 : 0);
}

void timer_cleanup (void)
{
	struct itimerval val = {{0, 0}, {0, 0}};

	setitimer (ITIMER_REAL, &val, NULL);
}

void timer_init (void)
{
	struct itimerval val = {{0, blink_interval}, {0, blink_interval}};

	ticks_max = ticks_bright + ticks_dark;

	xassert (setitimer(ITIMER_REAL, &val, NULL) != -1, "Ustawianie timera: %m.");

	xatexit (timer_cleanup);
}
