/*
 * Copyright 2009 Funambol, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

#include "Timer.h"
#include "Logger/LoggerMacroses.h"


using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_Common;

const char* const c_LogName = "Timer";

Timer::Timer() :
	m_isRunning(false), m_terminate(false), m_pulsesCount(0), m_pulsesPerInterval(0), m_ticksCount(0), m_ticksToCount(0), m_timerInterval(0), 
	m_callback(NULL)
{
}


Timer::~Timer()
{
	Stop();
}


bool Timer::IsRunning()
{
	return m_isRunning;
}


void Timer::SetCallback(Callback *c)
{
	GDLDEBUG("Callback %p", c);
	m_callback = c;
}


void Timer::SetInterval(uint seconds)
{
	m_timerInterval = seconds;
	m_pulsesPerInterval = m_timerInterval;
}


void Timer::SetTicksCount(int count)
{
	m_ticksCount = count;
}


void Timer::Start()
{
	if (m_isRunning) return;

	if (m_timerInterval)
	{
		m_ticksToCount = m_ticksCount;
		if (m_ticksCount == -1 || m_ticksCount > 0)
			startTimer();
	}
}


void Timer::Stop()
{
	if (!m_isRunning) return;

	softTerminate();
	wait();

	m_isRunning = false;
	terminate = false;
}


void Timer::run()
{
	m_isRunning = true;
	
	// tick once
	if (m_ticksToCount)
		tick();
	
	if (m_ticksToCount)
		while (!terminate)
		{
			sleep(1000);
			if (terminate) break;
			if (++m_pulsesCount > m_pulsesPerInterval)
			{
				m_pulsesCount = 0;
				tick();
			}
		}

	terminate = false;
	m_isRunning = false;
}


void Timer::notifyCallback()
{
	if (m_callback) m_callback->Call();
}


void Timer::startTimer()
{
	if (m_isRunning) return;
	terminate = false;
	start();
}


void Timer::tick()
{
	if (m_ticksToCount == 0)
	{
		terminate = true;
	}
	else
	{
		if (m_ticksToCount > 0)
			--m_ticksToCount;
		notifyCallback();				
	}
}
