/*! \file pitimer.h
 * \brief Timer
*/
/*
    PIP - Platform Independent Primitives
    Timer
    Copyright (C) 2014  Ivan Pelipenko peri4ko@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, see <http://www.gnu.org/licenses/>.
*/

#ifndef PITIMER_H
#define PITIMER_H

#include "pithread.h"
#include "pitime.h"

typedef void (*TimerEvent)(void * , int );

class PIP_EXPORT PITimer
#ifndef PIP_TIMER_RT
: public PIThread
#else
: public PIObject
#endif
{
	PIOBJECT(PITimer)
public:
	
	//! \brief Constructs timer with execution function \b slot and common data \b data.
	PITimer(TimerEvent slot = 0, void * data = 0, bool threaded = true);
	PITimer(bool threaded);
	virtual ~PITimer();

	
	//! \brief Set custom data.
	void setData(void * data_) {data = data_;}
	
	//! \brief Set timer execution function.
	void setSlot(TimerEvent slot) {ret_func = slot;}
	
	//! \brief Returns current loop delay.
	double interval() const {return interval_;}
	
	EVENT_HANDLER0(void, reset) {
#  ifdef WINDOWS
		//t_st = GetCurrentTime();
		pc_st = __PIQueryPerformanceCounter();
#  elif defined(MAC_OS)
		clock_get_time(__pi_mac_clock, &t_st);
#  else
		clock_gettime(0, &t_st);
#  endif
	}
	EVENT_HANDLER1(void, start, int, msecs) {start(double(msecs));}
	EVENT_HANDLER1(void, start, double, msecs);
	EVENT_HANDLER2(void, deferredStart, double, interval_msecs, double, delay_msecs);
	EVENT_HANDLER2(void, deferredStart, double, interval_msecs, const PIDateTime &, start_datetime);
#ifndef PIP_TIMER_RT
	EVENT_HANDLER0(void, stop) {running_ = false; PIThread::stop();}
#else
	EVENT_HANDLER0(void, stop);
	EVENT_HANDLER0(bool, waitForFinish) {return waitForFinish(-1);}
	EVENT_HANDLER1(bool, waitForFinish, int, timeout_msecs);
	bool isRunning() const {return running_;}
	void needLockRun(bool need) {lockRun = need;}
	EVENT_HANDLER0(void, lock) {mutex_.lock();}
	EVENT_HANDLER0(void, unlock) {mutex_.unlock();}
#endif
	
	//! \brief Add frequency delimiter \b delim with optional delimiter slot \b slot.
	void addDelimiter(int delim, TimerEvent slot = 0) {ret_funcs << TimerSlot(slot, delim);}
	
	//! \brief Remove all frequency delimiters \b delim.
	void removeDelimiter(int delim) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].delim == delim) {ret_funcs.remove(i); i--;}}
	
	//! \brief Remove all frequency delimiters with slot \b slot.
	void removeDelimiter(TimerEvent slot) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot) {ret_funcs.remove(i); i--;}}
	
	//! \brief Remove all frequency delimiters \b delim with slot \b slot.
	void removeDelimiter(int delim, TimerEvent slot) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot && ret_funcs[i].delim == delim) {ret_funcs.remove(i); i--;}}
	void setDelimiterValue(int delim, int value) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].delim == delim) ret_funcs[i].tick = value;}
	void setDelimiterValue(TimerEvent slot, int value) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot) ret_funcs[i].tick = value;}
	void setDelimiterValue(int delim, TimerEvent slot, int value) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot && ret_funcs[i].delim == delim) ret_funcs[i].tick = value;}
	int delimiterValue(int delim) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].delim == delim) return ret_funcs[i].tick; return -1;}
	int delimiterValue(int delim, TimerEvent slot) {for (int i = 0; i < ret_funcs.size_s(); ++i) if (ret_funcs[i].slot == slot && ret_funcs[i].delim == delim) return ret_funcs[i].tick; return -1;}
	EVENT_HANDLER0(void, clearDelimiters) {ret_funcs.clear();}

	
	//! \brief Returns nanoseconds elapsed from last \a reset() execution or from timer creation.
	double elapsed_n(); // nanoseconds

	//! \brief Returns microseconds elapsed from last \a reset() execution or from timer creation.
	double elapsed_u(); // microseconds

	//! \brief Returns milliseconds elapsed from last \a reset() execution or from timer creation.
	double elapsed_m(); // milliseconds

	//! \brief Returns seconds elapsed from last \a reset() execution or from timer creation.
	double elapsed_s(); // seconds

	
	double reset_time_n(); // nanoseconds
	double reset_time_u(); // microseconds
	double reset_time_m(); // milliseconds
	double reset_time_s(); // seconds

	
	//! \brief Returns time mark of last \a reset() execution or timer creation.
	PISystemTime reset_time();


	//! \brief Returns nanoseconds representation of current system time.
	static double elapsed_system_n(); // nanoseconds

	//! \brief Returns microseconds representation of current system time.
	static double elapsed_system_u(); // microseconds

	//! \brief Returns milliseconds representation of current system time.
	static double elapsed_system_m(); // milliseconds

	//! \brief Returns seconds representation of current system time.
	static double elapsed_system_s(); // seconds


#ifdef PIP_TIMER_RT
	class TimerPool: public PIThread {
	public:
		TimerPool(): PIThread() {/*cout << "+++++new pool\n"; */ti = -1;}
		~TimerPool() {stop();}
		void add(PITimer * t) {mutex.lock(); timers << TimerPair(t, 0); mutex.unlock();}
		void remove(PITimer * t);
		bool isEmpty() const {return timers.isEmpty();}
		typedef PIPair<PITimer * , int> TimerPair;
	private:
		static void empty_handler(int) {}
		void begin();
		void run();
		void end() {/*cout << "pool end\n"; */if (ti != -1) timer_delete(timer); ti = -1;}
		int ti, si;
		sigset_t ss;
		sigevent se;
		sigval sv;
		itimerspec spec;

		timer_t timer;
		PIVector<TimerPair> timers;
		PIMutex mutex;
	};
	static void timer_event(sigval e);
	int ticks;
#endif
	
	EVENT2(timeout, void * , data, int, delimiter)
	
//! \handlers
//! \{
	
	/** \fn void reset()
	 * \brief Set internal time mark to current system time
	 * \details This function used for set start time mark. Later
	 * you can find out elapsed time from this time mark to any
	 * moment of time with \a elapsed_s(), \a elapsed_m(),
	 * \a elapsed_u() or \a elapsed_n() function.
	 * \sa \a elapsed_s(), \a elapsed_m(), \a elapsed_u(), \a elapsed_n() */
	
	/** \fn void start(int msecs)
	 * \brief Start timer with \b msecs loop delay
	 * \details Start execution of timer functions with frequency = 1 / msecs Hz. */
	
	/** \fn void start(double msecs)
	 * \brief Start timer with \b msecs loop delay
	 * \details Start execution of timer functions with frequency = 1. / msecs Hz.
	 * Instead of \a start(int msecs) function this variant allow start timer
	 * with frequencies more than 1 kHz. */
	
	//! \fn void stop()
	//! \brief Stop timer

	/** \fn void deferredStart(double interval_msecs, double delay_msecs)
	 * \brief Start timer with \b interval_msecs loop delay after \b delay_msecs delay.
	 * \details Timer wait \b delay_msecs milliseconds and then normally starts with
	 * \b interval_msecs loop delay.
	 * \sa \a void start(double msecs), \a void deferredStart(double interval_msecs, const PIDateTime & start_datetime) */

	/** \fn void deferredStart(double interval_msecs, const PIDateTime & start_datetime)
	 * \brief Start timer with \b interval_msecs loop delay after \b start_datetime date and time.
	 * \details Timer wait until \b start_datetime and then normally starts with
	 * \b interval_msecs loop delay.
	 * \sa \a void start(double msecs), \a void deferredStart(double interval_msecs, double delay_msecs) */
	 
	//! \fn void clearDelimiters()
	//! \brief Remove all frequency delimiters.
	
//! \}
//! \events
//! \{
	
	/** \fn void timeout(void * data, int delimiter)
	 * \brief Raise on timer tick
	 * \details \b Data can be set with function \a setData(void * data) or from constructor.
	 * \b Delimiter if frequency delimiter, 1 for main loop. */
	
	
//! \}
	
protected:
	//! Virtual timer execution function, similar to "slot" or event \a void timeout(void * data, int delimiter).
	//! By default is empty.
	virtual void tick(void * data, int delimiter) {;}

private:
#ifndef PIP_TIMER_RT
	void run();
	void end() {interval_ = 0.;}
	
	PISystemTime st_time, inc_time;
	bool deferred_;
#else
	bool threaded;
	volatile bool lockRun;
	PIMutex mutex_;
	int ti;
	itimerspec spec;
	timer_t timer;
	sigevent se;
#endif
	bool running_;
	double interval_;

#ifdef WINDOWS
	llong pc_st, pc_cur, tt_st, tt_cur;
	long
#elif defined(MAC_OS)
	mach_timespec_t
#else
	timespec
#endif
		t_st, t_cur;

	struct TimerSlot {
		TimerSlot(TimerEvent slot_ = 0, int delim_ = 1) {slot = slot_; delim = delim_; tick = 0;}
		TimerEvent slot;
		int delim;
		int tick;
	};

	void * data;
	TimerEvent ret_func;
	PIVector<TimerSlot> ret_funcs;

};

#ifdef PIP_TIMER_RT
extern PITimer::TimerPool * pool;
#endif

#endif // PITIMER_H
