/* 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/>.
 */

#pragma once

#include "roar11/ThreadPool.hpp"
#include <exception>
#if __cplusplus <= 201703L
#	include <tuple>
#endif
#include <utility>

namespace eve {
class Eventia;
} //namespace eve

namespace duck {

class EventiaThreadPool : roar11::ThreadPool {
public:
	explicit EventiaThreadPool (eve::Eventia* eventia);
	EventiaThreadPool (eve::Eventia* eventia, std::uint32_t num_threads);
	~EventiaThreadPool() noexcept;

	template <typename Func, typename... Args>
	auto submit(Func&& func, Args&&... args);

	void wait() noexcept;

private:
	void set_exception (std::exception_ptr ptr);

	eve::Eventia* m_eventia;
};

template <typename Func, typename... Args>
inline
auto EventiaThreadPool::submit(Func&& func, Args&&... args) {
	using std::forward;

	auto catching_lambda =
#if __cplusplus <= 201703L
	[this,func=forward<Func>(func), args=std::make_tuple(forward<Args>(args)...)]() mutable {
		try {
			std::apply(func, std::move(args));
		}
#else
	[this,func=forward<Func>(func), ... args=forward<Args>(args)](){
		try {
			func(std::forward<Args>(args)...);
		}
#endif
		catch (...) {
			roar11::ThreadPool::invalidate();
			this->set_exception(std::current_exception());
		}
	};

	return roar11::ThreadPool::submit(std::move(catching_lambda));
}

} //namespace duck
