/* 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 "event.hpp"
#include "eventia.hpp"
#include "private/context.hpp"
#include <cassert>
#if !defined(NDEBUG)
#	ifdef __GNUG__
#		include <cstdlib>
#		include <memory>
#		include <cxxabi.h>
#	endif
#endif

namespace eve {

Event::Event (const Context& ctx) :
	m_eventia(ctx.eventia),
	m_was_stopped(false)
{
	assert(m_eventia);
	m_cb_id = m_eventia->register_stop_callback([this](){this->on_loop_stopping_local();});
}

Event::~Event() noexcept {
	m_eventia->unregister_stop_callback(m_cb_id);
}

void Event::on_loop_stopping_local() noexcept {
	this->on_loop_stopping();
}

void Event::set_exception (std::exception_ptr ptr) {
	m_eventia->set_exception(ptr);
}

bool Event::is_stopped() const noexcept {
	return m_was_stopped;
}

#if !defined(NDEBUG)
std::string Event::demangle (const char* name) {
	//see:
	//https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname

#ifdef __GNUG__
	int status = -4; // some arbitrary value to eliminate the compiler warning

	// enable c++11 by passing the flag -std=c++11 to g++
	std::unique_ptr<char, void(*)(void*)> res {
		abi::__cxa_demangle(name, NULL, NULL, &status),
		std::free
	};

	return (status==0) ? res.get() : name ;
#else
	// does nothing if not g++
    return name;
#endif
}
#endif

} //namespace eve
