/* 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 "signal.hpp"
#include "private/context.hpp"
#include <ev++.h>
#include <mutex>
#include <cassert>
#if !defined(NDEBUG)
#	include <iostream>
#endif

namespace eve {
namespace {
} //unnamed namespace

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

	ev::sig signal;
	Context context;
	int sig_num;
};

Signal::LocalData::LocalData (const Context& ctx) :
	context(ctx),
	sig_num(0)
{
}

Signal::Signal (int sig, const Context& ctx) :
	Event(ctx),
	m_local(std::make_unique<LocalData>(ctx))
{
	assert(m_local->context.ev_mutex);

	m_local->signal.set(*m_local->context.loop);
	m_local->signal.set<Signal, &Signal::on_signal_ev>(this);

	{
		std::unique_lock<std::mutex> lock(*m_local->context.ev_mutex);
		m_local->signal.set(sig);
		m_local->signal.start();
		m_local->context.async->send();
	}
}

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

void Signal::on_signal_ev() {
	this->on_signal();
}

void Signal::on_loop_stopping() noexcept {
	stop_ifn(m_local->signal);
}

} //namespace eve
