/*
 * Copyright (C) 2014 Julian Lewis
 * @author Federico Vaga <federico.vaga@gmail.com>
 *
 * 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, you may find one here:
 * http://www.gnu.org/licenses/gpl-3.0-standalone.html
 * or you may search the http://www.gnu.org website for the version 3 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include <libfwatch.h>

/**
 * It executes all handler associated associated to an application an
 * matching the given event type. The execution depends on the declaration
 * order
 */
int fwatch_event_input_handler(struct application *app, struct event *evt)
{
	struct app_evt_callback *cur;
	unsigned int i;
	int ret = 0;

	/* Go through all event handler associated to an application */
	for (i = 0; i < app->event_handlers_n; i++) {
		cur = &app->event_handlers[i];
		if (evt->type != cur->type)
			continue;
		if (cur->callback)
			ret |= cur->callback(app, evt);
	}

	return ret;
}


/**
 * Run a given fore-groung application
 */
int fwatch_application_run(struct application *app)
{
	int err = 0;

	if (app->setup) {
		err = app->setup(app);
		if (err)
			return err;
	}

	if (app->loop) {
		app->flags |= APP_FLAGS_RUN;
		while(fwatch_is_application_running(app))
			app->loop(app);
	}

	/* Application execution over, quit */
	if (app->quit)
		app->quit(app);
	return 0;
}
