/*
    libmaus2
    Copyright (C) 2019 German Tischler

    This program 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.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#if ! defined(LIBMAUS2_PARALLEL_STDTHREAD_HPP)
#define LIBMAUS2_PARALLEL_STDTHREAD_HPP

#include <thread>
#include <cassert>
#include <libmaus2/exception/LibMausException.hpp>

namespace libmaus2
{
	namespace parallel
	{
		struct StdThreadCallable
		{
			typedef StdThreadCallable this_type;
			typedef std::unique_ptr<this_type> unique_ptr_type;

			virtual ~StdThreadCallable() {}
			virtual void run() = 0;
		};

		struct StdThreadJoin
		{
			std::unique_ptr<std::thread> & thread;

			StdThreadJoin(std::unique_ptr<std::thread> & rthread)
			: thread(rthread)
			{
			}

			~StdThreadJoin()
			{
				try
				{
					if ( thread )
					{
						thread->join();
						thread.reset();
					}
				}
				catch(std::exception const & ex)
				{
					std::cerr << ex.what() << std::endl;
				}
			}
		};

		struct StdThread
		{
			typedef StdThread this_type;
			typedef std::unique_ptr<this_type> unique_ptr_type;
			typedef std::shared_ptr<this_type> shared_ptr_type;

			private:
			std::string const name;

			StdThreadCallable::unique_ptr_type callable;
			std::unique_ptr<std::thread> thread;
			StdThreadJoin stdjoin;
			libmaus2::exception::LibMausException::unique_ptr_type plme;

			// thread produced an uncaught exception
			std::atomic<int> failed_flag;
			std::atomic<int> exception_flag;
			std::atomic<int> exception_handling_failed_flag;
			std::atomic<int> ended_flag;

			static void dispatch(StdThread * ptr)
			{
				try
				{
					try
					{
						ptr->setName();
						ptr->callable->run();
					}
					catch(libmaus2::exception::LibMausException const & lme)
					{
						ptr->failed_flag = 1;

						libmaus2::exception::LibMausException::unique_ptr_type tlme(lme.uclone());
						ptr->plme = std::move(tlme);

						ptr->exception_flag = 1;
					}
					catch(std::exception const & ex)
					{
						ptr->failed_flag = 1;

						libmaus2::exception::LibMausException::unique_ptr_type tlme(new libmaus2::exception::LibMausException);
						tlme->getStream() << ex.what();
						tlme->finish();
						ptr->plme = std::move(tlme);

						ptr->exception_flag = 1;
					}
					catch(...)
					{
						ptr->failed_flag = 1;

						libmaus2::exception::LibMausException::unique_ptr_type tlme(new libmaus2::exception::LibMausException);
						tlme->getStream() << "[E] StdThread::dispatch: caught unknown exception" << std::endl;
						tlme->finish();
						ptr->plme = std::move(tlme);

						ptr->exception_flag = 1;
					}
				}
				catch(...)
				{
					ptr->exception_handling_failed_flag = 1;
				}

				ptr->ended_flag = 1;
			}

			public:
			StdThread(
				StdThreadCallable::unique_ptr_type & rcallable,
				std::string const & rname = std::string()
			)
			: name(rname), callable(std::move(rcallable)), thread(), stdjoin(thread),
			  failed_flag(0),
			  exception_flag(0),
			  exception_handling_failed_flag(0),
			  ended_flag(0)
			{}
			virtual ~StdThread() {}

			StdThreadCallable const & getCallable() const
			{
				return *callable;
			}

			StdThreadCallable & getCallable()
			{
				return *callable;
			}

			std::thread::id get_id() const
			{
				if ( thread )
					return thread->get_id();
				else
					return std::thread::id();
			}

			void start()
			{
				std::unique_ptr<std::thread> tthread(
					new std::thread(dispatch,this)
				);
				thread = std::move(tthread);
			}

			void tryJoin()
			{
				if ( thread )
				{
					thread->join();
					thread.reset();
				}
			}

			bool failed() const
			{
				return (failed_flag != 0);
			}

			void checkFailed()
			{
				if ( failed() )
				{
					// wait until thread has ended
					tryJoin();

					if ( exception_flag )
					{
						assert ( plme );
						throw *plme;
					}
					else
					{
						libmaus2::exception::LibMausException lme;
						lme.getStream() << "[E] exception occurred during thread exception handling" << std::endl;
						lme.finish();
						throw lme;
					}
				}
			}

			void join()
			{
				if ( thread )
				{
					tryJoin();
				}
				else
				{
					libmaus2::exception::LibMausException lme;
					lme.getStream() << "[E] StdThread::join: thread not set" << std::endl;
					lme.finish();
					throw lme;
				}
			}


			void setName()
			{
				if ( name.size() )
				{
					#if defined(LIBMAUS2_HAVE_PRCTL) && defined(PR_SET_NAME)
					prctl(PR_SET_NAME,name.c_str(),0,0,0);
					#endif
				}
			}
		};
	}
}
#endif
