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

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

#define MESSAGE_QUEUE_KEY 642656000


CWorkerNetworkStatSender::CWorkerNetworkStatSender()
{

}

CWorkerNetworkStatSender::~CWorkerNetworkStatSender()
{

}


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

    if (m_pid == 0)
    {   
        
        while (*sighandle == 0)
        {   
            // work
            set_ps_display("Worker [Network stat sender]", false);
            do_work(sighandle);
            
            // signal 받은 경우 wait 불필요
            if(*sighandle == 0)
            {   
                pause();
            }
        }
        
        // httpd 구동 여부에 따라 Detache or Destroy를 결정함
        if(IsProcessRun("httpd") == true)
        {           
            m_shmemNetworStat.Detach();
            LOG(LDBG, "m_shmemNetworStat.Detach()");
        }                                                           
        else    
        {                   
            m_shmemNetworStat.Destroy();
            LOG(LDBG, "m_shmemNetworStat.Destroy()");
        }                                                                   

        m_launched = false;
    }

    return m_pid;
}



void CWorkerNetworkStatSender::do_work(const sig_atomic_t *sighandle)
{
	apr_pool_t *p;
	apr_pool_create(&p, NULL);

	// account shared memory 생성
	int nMaxAccount = CDeamonConfig::GetInstance()->GetMaxAccount();
	int nNeworkStatSize = (sizeof(struct service_network_stat) * nMaxAccount * 2);

	if (m_shmemNetworStat.Create("/tmp/opendav.shared.networkstat.shm", nNeworkStatSize, p) == false)
	{
		LOG(LERR, "Networkstat shared memory create failed.");
		exit(EXIT_FAILURE);
	}

	SetThreadSignal(SIGINT);
	SetThreadSignal(SIGTERM);

	if( m_objNetworkStatSendThread.ThreadInit(sighandle, &m_shmemNetworStat ) == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "Network stat send thread create failed.");
		exit(EXIT_FAILURE);
	}
	if( m_objNetworkStatSendThread.Start() == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "Network stat send thread start failed.");
		exit(EXIT_FAILURE);
	}
	UnSetThreadSignal(SIGINT);
	UnSetThreadSignal(SIGTERM);
}
