#include "Worker.h"
#include <sstream>

#include "Logger.h"
#include "DaemonConfigs.h"



CWorker::CWorker()
{

}

CWorker::~CWorker()
{

}

pid_t CWorker::Launcher(const sig_atomic_t *sighandle)
{
	Fork();

	if (m_pid == 0)
	{
	
		while (*sighandle == 0)
		{
			// work
			set_ps_display("Worker [log management process]", false);
			do_work(sighandle);
			
			// signal 받은 경우 wait 불필요
			if(*sighandle == 0)
			{
				pause();
			}
		}

		// TODO : 워커 종료시에 필요한 부분을 코딩하면 된다.
		// ....

		m_launched = false;
	}

	return m_pid;
}


void CWorker::do_work(const sig_atomic_t *sighandle)
{
	SetThreadSignal(SIGINT);
	SetThreadSignal(SIGTERM);

	if( m_objLogFileCleaner.ThreadInit(sighandle) == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "Log Cleaner init failed.");
		exit(EXIT_FAILURE);

	}
	if( m_objLogFileSender.ThreadInit(sighandle) == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "Log Sender init failed.");
		exit(EXIT_FAILURE);
	}

	if( m_objLogFileCleaner.Start() == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "Log Cleaner startfailed.");
		exit(EXIT_FAILURE);
	}
	
	if( m_objLogFileSender.Start() == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "Log Sender startfailed.");
		exit(EXIT_FAILURE);
	}

	UnSetThreadSignal(SIGINT);
	UnSetThreadSignal(SIGTERM);
}
