#include "engine/declarations.h"

#include "declarations_app.h"
#include "worker_roller.h"



void worker_roller(void *ta) {
	struct t_ctx *ti;

	D_TIME_TV tv;

	ti = (struct t_ctx *) ta;

	/* This thread does not like to receive pthread_cancel() */
	ti->ar = THREAD_TERM_SELF;

	pthread_cleanup_push(worker_roller_cancel, ti);

	if(worker_roller_init(ti) == 0) {
		while(ti->pr == THREAD_STATE_RUN) {
			(void) roller_loop_begin((struct t_str *) ti->tp, &tv);

			(void) universe_run();

			(void) roller_loop_end(&tv);
		}
	}

	/* Free allocated resources and terminate thread */
	pthread_cleanup_pop(1);

	(void) worker_roller_finalize(ti);
}

static void worker_roller_cancel(void *ta) {
	struct t_ctx *ti;

	ti = (struct t_ctx *) ta;

	if(ti->tp != NULL) {
		(void) worker_roller_cancel_local(ti,
			(struct t_str *) ti->tp);

		(void) free(ti->tp);

		ti->tp = NULL;
	}

	ti->tr = THREAD_STATE_STOP;
}

static void worker_roller_cancel_local(__UNUSED__ struct t_ctx *ti, __UNUSED__ struct t_str *tp) {
	(void) universe_free();
}

static void worker_roller_finalize(struct t_ctx *ti) {
	(void) thread_exit(ti, NULL);
}

static int worker_roller_init(struct t_ctx *ti) {
	int r;

	struct t_str *c;

	APP_MALLOC_RET_VALUE(c, sizeof(struct t_str), -1);

	ti->tp = c;

	(void) thread_title(ti, APPLICATION_EXEC "_roller");

	r = worker_roller_init_local(ti, (struct t_str *) ti->tp);

	ti->tr = THREAD_STATE_IDLE;

	return(r);
}

static int worker_roller_init_local(__UNUSED__ struct t_ctx *ti, __UNUSED__ struct t_str *tp) {
	return(universe_init());
}

static void roller_loop_begin(__UNUSED__ struct t_str *tp, D_TIME_TV *t) {
	(void) timer_get_time(t);
}

static void roller_loop_end(D_TIME_TV *t) {
	long n;

	D_TIME_TV v;

	(void) timer_get_time(&v);

	n = (long) (v.tv_usec - t->tv_usec);

	if(n < 0) {
		n = 1000000 + n;
	}

	n = ((1000000 / ROLLER_UPDATE_RPS) - n) * 1000;

	if(n > 0) {
		(void) timer_wait(0, n);
	}
}
