/*
 * Copyright 2010 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$ */

#pragma once

#include "commontypes.h"
#include "common/posix/Event.h"
#include <push/FThread.h>
#include <signal.h>
#include <pthread.h>

namespace NS_DM_Client
{
	namespace NS_Common
	{
		class Callback {
		public:
			virtual ~Callback() {}
			virtual void Call() = 0;
		};

		/// Class represents timer that triggers action each time it c
		class Timer : private Event
		{
		public:
			Timer();
			~Timer();

			/// Ask whether timer is running
			/// If TicksCount is set to number >0, timer will switch to non-running state afer all ticks runned
			bool IsRunning();

			/// Set timer's callback
			void SetCallback(Callback *c);

			/// Set timer interval in seconds
			void SetInterval(uint t);

			/// Set number of timer ticks
			/// @param count number of ticks; if -1 timer will ticks forever
			void SetTicksCount(int count);

			/// Start the timer. Will do nothing if timer is already started
			void Start();

			/// Stop the timer. Will do nothing if timer is not running
			void Stop();
			
		protected:
			friend void * ThreadBody(void *);

		private:
			volatile bool m_isRunning;
			volatile bool m_shouldRun;
			
			int  m_ticksCount; /// -1 - forever, 0 - not running,
			int  m_ticksToCount;
			uint m_timerInterval; /// timer interval, seccnds
			Callback *m_callback;
		
			pthread_t       m_thread;

			void notifyCallback();
			void startTimer();
			void tick();
		};
	}
}
