/* 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 "eventia.hpp"
#include "event.hpp"
#include "private/context.hpp"
#include <ev++.h>
#include <mutex>
#include <iostream>
#include <cassert>
#include <boost/container/flat_map.hpp>
#include <utility>
#include <future>
#include <stdexcept>
#include <atomic>
#include <exception>

namespace eve {

namespace {
	void lock_mutex_libev (struct ::ev_loop* ev) noexcept {
		Context* const ctx = static_cast<Context*>(ev_userdata(ev));
		ctx->ev_mutex->lock();
	}

	void unlock_mutex_libev (struct ::ev_loop* ev) noexcept {
		Context* const ctx = static_cast<Context*>(ev_userdata(ev));
		ctx->ev_mutex->unlock();
	}
} //unnamed namespace

struct Eventia::LocalData {
	explicit LocalData(Eventia* eventia);

	std::mutex ev_mutex;
	std::mutex exception_mutex;
	boost::container::flat_map<unsigned int, std::function<void()>> stop_cbs;
	ev::async async;
	ev::default_loop loop;
	Context context;
	std::promise<void> loop_end_promise;
	std::future<void> loop_end;
	std::atomic_bool errored_out;
	std::exception_ptr last_exception;
};

Eventia::LocalData::LocalData(Eventia* eventia) :
	loop(ev::AUTO),
	context{ &loop, &ev_mutex, &async, eventia },
	loop_end(loop_end_promise.get_future()),
	errored_out(false)
{
}

Eventia::Eventia() :
	m_local(std::make_unique<LocalData>(this))
{
	assert(nullptr == ev_userdata(m_local->loop));
	m_local->async.set(m_local->loop);
	m_local->async.set<Eventia, &Eventia::on_async>(this);
	m_local->async.start();
	ev_set_userdata(m_local->loop, &m_local->context);
	ev_set_loop_release_cb(m_local->loop, &eve::unlock_mutex_libev, &eve::lock_mutex_libev);
}

Eventia::~Eventia() noexcept = default;

std::function<void()> Eventia::event_functor() {
	return std::function<void()>([this]() {
		m_local->errored_out = false;
		m_local->last_exception = nullptr;
		std::unique_lock<std::mutex> lock(m_local->ev_mutex);
		m_local->loop.run(0);
#if !defined(NDEBUG)
		std::cout << "ev loop stopped\n";
#endif
		if (not m_local->errored_out) {
			m_local->loop_end_promise.set_value();
		}
		else {
			std::unique_lock lock(m_local->exception_mutex);
			m_local->loop_end_promise.set_exception(m_local->last_exception);
		}
	});
}

void Eventia::stop() noexcept {
#if !defined(NDEBUG)
	try {
		std::cout << "Stopping Eventia (" << m_local->stop_cbs.size() << " observers)...\n";
	}
	catch (...) {}
#endif
	for (auto& stop_cb : m_local->stop_cbs) {
		stop_cb.second();
	}
	m_local->loop.break_loop(ev::ALL);
}

void Eventia::wait() {
	m_local->loop_end.get();
}

void Eventia::set_exception (std::exception_ptr ptr) noexcept {
	try {
		std::unique_lock lock(m_local->exception_mutex);
		if (m_local->errored_out)
			return;

		m_local->last_exception = ptr;
		m_local->errored_out = true;
		m_local->async.send();
	}
	catch (const std::system_error& err) {
		std::cerr << "Unexpected exception in Eventia::set_exception(), this is bad! Exception message: " <<
			err.what() << '\n';
	}
}

void Eventia::lock_mutex_libev() noexcept {
	try {
		m_local->ev_mutex.lock();
	}
	catch (const std::system_error&) {
		assert(false);
		std::cerr << "Locking mutex failed, this will probably result in bad program behaviour\n";
	}
}

void Eventia::unlock_mutex_libev() noexcept {
	m_local->ev_mutex.unlock();
}

const Context& Eventia::context() {
	return m_local->context;
}

void Eventia::on_async() {
	if (m_local->errored_out) {
		m_local->async.stop();
		this->stop();
	}
}

unsigned int Eventia::register_stop_callback (std::function<void()>&& func) {
	const unsigned int id = static_cast<unsigned int>(m_local->stop_cbs.size());
	m_local->stop_cbs.insert(std::make_pair(id, std::move(func)));
	return id;
}

void Eventia::unregister_stop_callback (unsigned int id) noexcept {
	try {
		m_local->stop_cbs.erase(id);
	}
	catch (...) {
		assert(false);
	}
}

} //namespace eve
