/*!
 * UbusTimer.cpp
 *
 * Copyright (c) 2016, 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 "ubuscpp/UBusTimer.h"


/*!  ----------------------------------------------------------------------------
 *  @fn timer_callback
 *
 *  @brief Callback used when a Timer has expired.
 */
static void timer_callback (struct uloop_timeout *aTimeout)
{
	UBusTimer *aTmp = static_cast<UBusTimer *>(aTimeout);
	aTmp->Tick();
}


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

	// UBus Timer.
	mRepeat = false;
	mTimerValue = 0;
}


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


/*!  ----------------------------------------------------------------------------
 *  @fn Start the Timer
 *  
 *  @brief Start the Timer object.
 */
int UBusTimer::Start (unsigned int aTimerValue, bool aRepeat)
{
	mTimerValue = aTimerValue;
	mRepeat = aRepeat;

	return uloop_timeout_set (this, mTimerValue);
}


/*!  ----------------------------------------------------------------------------
 *  @fn Expire 
 *  
 *  @brief Method Should be overrided.
 */
int UBusTimer::Expire (void)
{
	//fprintf (stderr, "UBusTimer::Expire\n");
	return 0;
}


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

	if (mRepeat == true)
		uloop_timeout_set (this, mTimerValue);

	return 0;
}
