/* Copyright 2020, Michele Santullo
 * This file is part of orotool.
 *
 * Orotool 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.
 *
 * Orotool 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 Orotool.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "timer.hpp"
#include "private/context.hpp"
#include <ev++.h>
#include <mutex>
#include <cassert>
#include <algorithm>
#if !defined(NDEBUG)
#	include <iostream>
#endif
#include <exception>

namespace eve {

namespace {
	constexpr const double g_timer_max = 3600.0;
} //unnamed namespace

struct Timer::LocalData {
	explicit LocalData (const Context& ctx);

	ev::timer timer;
	Context context;
	double elapsed;
	double timeout;
	double timer_value;
};

Timer::LocalData::LocalData (const Context& ctx) :
	context(ctx),
	elapsed(0.0),
	timeout(0.0),
	timer_value(0.0)
{
}

Timer::Timer (double delay, const Context& ctx) :
	Event(ctx),
	m_local(std::make_unique<LocalData>(ctx))
{
	assert(m_local->context.ev_mutex);

	m_local->timer.set(*m_local->context.loop);
	m_local->timer.set<Timer, &Timer::on_timer_ev>(this);
	this->set_timer(delay);
}

Timer::~Timer() noexcept {
	Timer::on_loop_stopping();
}

void Timer::on_timer_ev() noexcept {
	try {
		double& elapsed = m_local->elapsed;
		const double& timer_value = m_local->timer_value;
		const double& timeout = m_local->timeout;

		elapsed += timer_value;
		if (elapsed >= timeout) {
			this->on_timer();
		}
		else {
			m_local->timer.start(std::min(timeout - elapsed, g_timer_max), 0.0);
		}
	}
	catch (...) {
		set_exception(std::current_exception());
	}
}

void Timer::set_timer (double delay) {
	std::unique_lock<std::mutex> lock(*m_local->context.ev_mutex);
	m_local->elapsed = 0.0;
	m_local->timeout = delay;
	m_local->timer_value = std::min(g_timer_max, m_local->timeout);

	if (this->is_stopped()) {
#if !defined(NDEBUG)
		std::cout << "Timer::set_timer(" << delay << ") refusing to act because underlying event was stopped\n";
#endif
		return;
	}

	m_local->timer.stop();
	ev_now_update(*m_local->context.loop);
	m_local->timer.start(m_local->timer_value, 0.0);
#if !defined(NDEBUG)
	std::cout << "Timer::set_timer(" << delay << ")\n";
#endif
	m_local->context.async->send();
}

void Timer::on_loop_stopping() noexcept {
	this->stop_ifn(m_local->timer);
}

} //namespace eve
