//---------------------------------------------------------------------------------
// <copyright file="LqrSMACAsynchronousProcessExecutor.h" company="LiquidRobotics">
//
// Copyright (c) 2014 Liquid Robotics, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// This software is associated with a release.  Liquid Robotics makes no
// representation that the design, interfaces or component distribution will
// remain unchanged in future releases.
//
// </copyright>
//
// <summary>
//   Declaration of AsynchronousProcessExecutor, which encapsulates asynchronous
//   execution of a process and fires events for process output and exit of the
//   process.
// </summary>
//
// <owner>Mike Cookson</owner>
//---------------------------------------------------------------------------------

#ifndef __LQRSMACASYNCHRONOUSPROCESSEXECUTOR_H__
#define __LQRSMACASYNCHRONOUSPROCESSEXECUTOR_H__

#include "LqrSMACByteArray.h"
#include "LqrSMACDeclareException.h"
#include "LqrSMACLockableConcept.h"
#include "LqrSMACLogger.h"
#include "LqrSMACPipes.h"
#include "LqrSMACSemaphore.h"
#include "LqrSMACSharedLib.h"
#include <stdexcept>
#include <string>
#include <vector>
#include <signal.h>
#include <boost/shared_ptr.hpp>
#include <boost/signals2.hpp>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/recursive_mutex.hpp>

namespace LiquidRobotics {
namespace SMACFramework {

class SHARED_LIB_PUBLIC AsynchronousProcessExecutor
: public LockableConceptMutex
, boost::noncopyable
{
public:

	DECLARE_EXCEPTION(ExecFailed, std::runtime_error);
	DECLARE_EXCEPTION(SystemError, std::runtime_error);

	typedef LiquidRobotics::SMACFramework::ByteArray ByteArray;
	typedef LiquidRobotics::SMACFramework::Logger Logger;
	typedef LiquidRobotics::SMACFramework::Pipes Pipes;
	typedef boost::shared_ptr<AsynchronousProcessExecutor> Ptr;
	typedef boost::signals2::scoped_connection ScopedConnection;
	typedef boost::shared_ptr<ScopedConnection> ScopedConnectionPtr;
	typedef std::string string;
	typedef std::vector<string> StringArray;
	typedef boost::shared_ptr<StringArray> StringArrayPtr;
	typedef boost::signals2::signal<void (AsynchronousProcessExecutor& sender, int resultCode)> ExitSignalType;
	typedef boost::signals2::signal<void (AsynchronousProcessExecutor& sender, const ByteArray& dataReceived, bool fromStdErr)> ReportSignalType;

	class BackgroundThreadRunResult
	{
	public:

		typedef boost::shared_ptr<BackgroundThreadRunResult> Ptr;
		typedef LiquidRobotics::SMACFramework::Semaphore Semaphore;

		BackgroundThreadRunResult();

		void AwaitResult();
		void ReportExecFail(const string& msg);
		void ReportSystemErr(const string& msg);
		void ReportSuccess();

	private:

		Semaphore sem;
		string exceptionText;
		bool systemErr;
	};

	AsynchronousProcessExecutor(Logger::Ptr _logger = Logger::Ptr()
							  , int _defaultKillSignal = SIGTERM
							  , bool _killOnDelete = true
							  , int _deleteKillSignal = SIGKILL
							  , int _pollingMilliseconds = 500
							  , bool _routeStdErrToStdOut = false
							  , size_t _readSize = 1024);

	AsynchronousProcessExecutor(Logger& _logger
							  , int _defaultKillSignal = SIGTERM
							  , bool _killOnDelete = true
							  , int _deleteKillSignal = SIGKILL
							  , int _pollingMilliseconds = 500
							  , bool _routeStdErrToStdOut = false
							  , size_t _readSize = 1024);

	~AsynchronousProcessExecutor();

	bool GetExtremelyVerbose() const;
	void SetExtremelyVerbose(bool newValue = true);
	int GetResultCode() const;  // use WIFEXITED and WEXITSTATUS to determine the true status
	void Kill();
	void Kill(int sigNum);
	bool ProcessExecuting() const;
	bool ProcessExited() const;
	void RunAsynch(const string& commandLine, bool usePath = true, bool enableReadPipe = false);
	void RunAsynch(const StringArray& commandTokens, bool usePath = true, bool enableReadPipe = false);
	ScopedConnectionPtr SubscribeExitSignal(ExitSignalType::slot_type slot);
	ScopedConnectionPtr SubscribeReportSignal(ReportSignalType::slot_type slot);

	ExitSignalType ExitSignal;
	ReportSignalType ReportSignal;

private:

	typedef std::vector<char> CharArray;

	//friend class boost::detail::thread_data<boost::reference_wrapper<AsynchronousProcessExecutor> >;

	template<typename CMDTYPE>
	void BackgroundThread(CMDTYPE commandLine, bool usePath, bool enableReadPipe, BackgroundThreadRunResult::Ptr runResult);
	//void BackgroundThread(string commandLine, bool usePath, bool enableReadPipe, BackgroundThreadRunResult::Ptr runResult);
	//void BackgroundThread(StringArrayPtr commandTokens, bool usePath, bool enableReadPipe, BackgroundThreadRunResult::Ptr runResult);

	template<typename CMDTYPE>
	void DoExec(Pipes::Ptr& procPipe, Pipes::Ptr& procPipe2, Pipes::Ptr& readPipe, Pipes::Ptr& errPipe, CMDTYPE commandLine, bool usePath, bool enableReadPipe,
			BackgroundThreadRunResult::Ptr runResult);

	void DoExec(const string& commandLine, bool usePath);
	void DoExec(const StringArray& commandTokens, bool usePath);

	template<typename CMDTYPE>
	void ExecChild(Pipes::Ptr& procPipe, Pipes::Ptr& procPipe2, Pipes::Ptr& readPipe, Pipes::Ptr& errPipe, CMDTYPE& commandLine,
			bool usePath, BackgroundThreadRunResult::Ptr runResult);

	template<typename CMDTYPE>
	void ExecParentStart(Pipes::Ptr& procPipe, Pipes::Ptr& procPipe2, Pipes::Ptr& readPipe, Pipes::Ptr& errPipe, CMDTYPE& commandLine,
			BackgroundThreadRunResult::Ptr runResult);

	static string GetCommandLineSummary(const string& cmdLine);
	static string GetCommandLineSummary(const StringArray& cmdLine);

	void ExecParentComplete(Pipes::Ptr& procPipe, Pipes::Ptr& readPipe, Pipes::Ptr& errPipe);
	bool ReportProcessOutput(int fd, bool fromStdErr, Lock& theLock);
	static bool CheckedKill(pid_t pid, int sigType, bool throwIfBadPID = false);

	bool HaveLogger() const;
	Logger& GetLogger() const;

	Logger::Ptr logger;
	Logger* loggerPtr;
	const int defaultKillSignal;
	const bool killOnDelete;
	const int deleteKillSignal;
	const int pollingMilliseconds;
	const bool routeStdErrToStdOut;
	const size_t readSize;
	bool extremelyVerbose;
	bool runningCommand;
	Pipes::Ptr shutdownPipe;
	int resultCode;
	boost::thread* pThread;
	pid_t pid;
	bool exited;
};

}
}

#endif
