/*!
 *
 * Copyright (c) 2016-2018, NADAL Jean-Baptiste. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 * 
 * @Author:  NADAL Jean-Baptiste
 * @Date: 17/05/2016
 *
 */

/*-------------------------------- INCLUDES ---------------------------------*/

#include <cstdio>

#include "ubus-cpp/uloop-timer.h"

/*!  ----------------------------------------------------------------------------
 *  @fn timer_callback
 *
 *  @brief Callback used when a Timer has expired.
 */
static void timer_callback(struct uloop_timeout *a_timeout)
{
	ULoopTimer *the_timer = static_cast<ULoopTimer *>(a_timeout);

	the_timer->tick();
}

/*!  ----------------------------------------------------------------------------
 *  @fn ULoopTimer
 *
 *  @brief Constructor of the Uloop Timer Object.
 */
ULoopTimer::ULoopTimer(void)
{
	// Uloop Timer Init.
	cb = timer_callback;
	pending = 0;

	// UBus Timer.
	m_is_repeated = false;
	m_timer_value = 0;
}

/*!  ----------------------------------------------------------------------------
 *  @fn ~ULoopTimer
 *
 *  @brief Destructor of the Ullop Timer Object.
 */
ULoopTimer::~ULoopTimer(void)
{
}

/*!  ----------------------------------------------------------------------------
 *  @fn start
 *  @param aTimerValue is the amount of time (in milliseconds) before the timer
 *  	expires.
 *  @brief Start the Timer object.
 */
int ULoopTimer::start(unsigned int a_timer_value, bool a_is_repeated)
{
	m_timer_value = a_timer_value;
	m_is_repeated = a_is_repeated;

	return uloop_timeout_set(this, m_timer_value);
}

/*!  ----------------------------------------------------------------------------
 *  @fn stop
 *  
 *  @brief Stop the Timer object.
 */
int ULoopTimer::stop(void)
{
	return uloop_timeout_cancel(this);
}

/*!  ----------------------------------------------------------------------------
 *  @fn tick
 *
 *  @brief Method called when the Timer has expired.
 */
int ULoopTimer::tick(void)
{
	// fprintf (stderr, "UBusTimer::Tick\n");

	if (m_is_repeated == true)
		uloop_timeout_set(this, m_timer_value);

	return expire();
}
