#ifndef __MyuProcessManager_H__
#define __MyuProcessManager_H__

#include <mwlcommon.h>
#include <string>

//	クラス宣言
class CMyuProcessManager
{
private:
	//	プロセス情報系
	STARTUPINFO m_si;
	PROCESS_INFORMATION m_pi;
	DWORD m_dwCreationFlags;

	//	内部情報系
	std::string m_strCurDir;

	void Clear_First(){
		ZeroMemory(&m_si,sizeof(m_si));
		ZeroMemory(&m_pi,sizeof(m_pi));
		m_si.cb = sizeof(m_si);
		m_dwCreationFlags = 0;
	}
	void ReleaseProcHandles(){
		SAFE_CLOSE_HANDLE(m_pi.hThread);
		SAFE_CLOSE_HANDLE(m_pi.hProcess);
	}

public:
	//	コンストラクタ・デストラクタ
	CMyuProcessManager(){ Clear_First(); }
	virtual ~CMyuProcessManager(){
		/*//	まだ生きてたらとりあえず強制的に殺しちゃう♪（ォィ
		if ( IsAlive() )
			TerminateProcess( GetProcessHandle(), -1 );*/
		//WaitEnd();
		ReleaseProcHandles();
	}

	//	作成系
	BOOL Create( const char* lpApplicationName, const char* lpCommandLine );
	BOOL Create( const char* lpCommandLine ){ return Create(NULL, lpCommandLine ); }
	/*BOOL ThrustCreate( const char* lpApplicationName, const char* lpCommandLine ){
		if ( Create( lpApplicationName, lpCommandLine ) != TRUE )
			return FALSE;
		Detach();
		return TRUE;
	}
	BOOL ThrustCreate( const char* lpCommandLine ){ return ThrustCreate(NULL, lpCommandLine ); }*/
	BOOL WaitEnd( LPDWORD dwpRetCode=NULL, DWORD dwTimeOut=INFINITE );
	DWORD GetExitCode( DWORD dwErrDefault=0xffffffff );
	BOOL GetExitCodeEx( LPDWORD dwpRetCode );
	BOOL IsAlive(){
		if ( m_pi.hProcess == NULL )	//	チェック
			return FALSE;

		if ( WaitForSingleObject(m_pi.hProcess,0) == WAIT_TIMEOUT )
			return TRUE;
		else
			return FALSE;
	}

	//	開放系
	BOOL Clear(){
		if ( IsAlive() )
			return FALSE;
		ReleaseProcHandles();
		Clear_First();
		return TRUE;
	}
	void Close(){
		if ( IsAlive() )
			TerminateProcess( m_pi.hProcess, -99 );
		ReleaseProcHandles();
		Clear_First();
	}
	void Detach(){ ReleaseProcHandles(); }

	//	セッティング系
	void SetCurDir( const char* szPath ){ m_strCurDir = szPath; }
	void SetCurDirHere( HMODULE hModule=NULL );
	void SetStdoutHandle( HANDLE hStdout ){ m_si.hStdOutput = hStdout; m_si.dwFlags |= STARTF_USESTDHANDLES; }
	void SetHideConsole(){ m_dwCreationFlags |= CREATE_NO_WINDOW; }

	//	取得
	PROCESS_INFORMATION* GetProcInfoPtr(){ return &m_pi; }
	HANDLE GetProcessHandle(){ return m_pi.hProcess; }
};

#endif//__MyuProcessManager_H__