/*
 * Kangaroo Punch MultiPlayer Game Server Mark II
 * Copyright (C) 2020-2021  Scott Duensing
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */


#include "timer.h"


static void timerPaint(WidgetT *widget, uint8_t enabled, RectT pos);


WidgetT *timerInit(WidgetT *widget, widgetCallback timeout, uint16_t quarterSeconds) {
	TimerT *t = (TimerT *)widget;

	t->running          = 1;
	t->counter          = 0;
	t->quarterSeconds   = quarterSeconds;
	t->timeout          = timeout;
	t->base.paintMethod = timerPaint;

	// We use the paint event to handle timer processing.
	GUI_SET_FLAG(widget, WIDGET_FLAG_ALWAYS_PAINT);

	return widget;
}


TimerT *timerNew(widgetCallback timeout, uint16_t quarterSeconds) {
	TimerT   *timer = (TimerT *)malloc(sizeof(TimerT));
	WidgetT  *widget  = NULL;

	if (!timer) return NULL;

	widget = widgetInit(W(timer), MAGIC_TIMER, 0, 0, 0, 0, 0, 0, 0, 0);
	if (!widget) {
		free(timer);
		return NULL;
	}

	timer = (TimerT *)timerInit((WidgetT *)timer, timeout, quarterSeconds);
	if (!timer) {
		free(timer);
		return NULL;
	}

	return timer;
}


static void timerPaint(WidgetT *widget, uint8_t enabled, RectT pos) {
	TimerT   *t     = (TimerT *)widget;

	(void)enabled;
	(void)pos;

	// Do we care?
	if (t->running) {
		// Everything ticks off the quarter second.
		if (guiTimerQuarterSecondTick()) t->counter++;
		// We don't check for timeout inside the tick condition so that timers of 0 fire immediately.
		if (t->counter >= t->quarterSeconds) {
			// Timeout!  Call user.
			guiPendingEventAdd(widget, t->timeout);
			t->counter = 0;
		}
	}
}


void timerQuarterSecondsSet(TimerT *timer, uint16_t quarterSeconds) {
	timer->quarterSeconds = quarterSeconds;
	timer->counter        = 0;
}


void timerReset(TimerT *timer) {
	timer->counter = 0;
}


void timerStart(TimerT *timer) {
	timer->counter = 0;
	timer->running = 1;
}


void timerStop(TimerT *timer) {
	timer->running = 0;
}


void timerTimeoutSet(TimerT *timer, widgetCallback timeout) {
	timer->timeout = timeout;
}
