
#include "DirectLaneSend.h"
#include "tagbl_struc.h"
#include "file_no.h"

char g_szProcessname[MAX_STRING_SIZE + 1];
char g_szProcessPath[PATH_MAX + 1];
char retData[MAX_STRING_SIZE + 1];
int retlen;

int DirectLaneSend(char *rebuff, char *argv[])
{
    char szProcessname[PATH_MAX + 1];
    char *pFindPointer;
    //int nPathIndicatorPos;
    int nResult;

    //DaemonStart();
/*
    nResult = SafeStrCopy(szProcessname, sizeof(szProcessname), argv[0]);
    if (nResult != SEC_ERR_SUCCESS)
    {
        printf_s("strcpy_s Error![%d]\n", nResult);
    }
    pFindPointer = szProcessname;
    nResult = SafeStrrChr(szProcessname, strnlen_s(szProcessname, sizeof(szProcessname)), '/', &pFindPointer);

    printf_s("szProcess Name : %s\n", szProcessname);

    if (pFindPointer == NULL)
    {
        nResult = SafeStrCopy(g_szProcessname, sizeof(g_szProcessname), szProcessname);
    }
    else
    {
        nResult = SafeStrCopy(g_szProcessname, sizeof(g_szProcessname), pFindPointer + 1);
    }

    GetExecPath(g_szProcessPath, sizeof(g_szProcessPath) - 1, argv[0]);
    printf_s("g_szProcess Name : %s\n", g_szProcessname);
    if (g_szProcessPath == NULL)
    {
        printf_s("Can't get process path[Cann't load config file]!\nExit Program!");
        return -1;
    }

    nResult = InitMessageProcessConfig();

    if (nResult != MQ_ERR_SUCCESS)
    {
        printf_s("Program terminated!!!\n");
        return -1;
    }
*/
    WriteLog(LogType_SystemOut,LogLevel_Info, "Process Started![%s]", g_szProcessname);

    /* Socket 처리 루프 : 종료시 프로그램 종료됨 */
    nResult = InitThread(WorkThread);
    sprintf((char *)rebuff, "%s", retData);
    WriteLog(LogType_SystemOut,LogLevel_Info, "Process Stopped![%s]", g_szProcessname);

    return 0;
}

int InitMessageProcessConfig(int argc, char *argv[])
{
    char szConfigfilename[PATH_MAX + 1];
    char szConfigfilenameTemp[PATH_MAX + 1];
	char szProcessname[PATH_MAX + 1];
	int nResult, nLane_no, options;
	char *pFindPointer;
	char plz_id[2];

    nResult = SafeStrCopy(szProcessname, sizeof(szProcessname), argv[0]);
    if (nResult != SEC_ERR_SUCCESS)
    {
        printf_s("strcpy_s Error![%d]\n", nResult);
    }
    pFindPointer = szProcessname;
    nResult = SafeStrrChr(szProcessname, strnlen_s(szProcessname, sizeof(szProcessname)), '/', &pFindPointer);

    printf_s("szProcess Name : %s\n", szProcessname);

    if (pFindPointer == NULL)
    {
        nResult = SafeStrCopy(g_szProcessname, sizeof(g_szProcessname), szProcessname);
    }
    else
    {
        nResult = SafeStrCopy(g_szProcessname, sizeof(g_szProcessname), pFindPointer + 1);
    }

    GetExecPath(g_szProcessPath, sizeof(g_szProcessPath) - 1, argv[0]);
    printf_s("g_szProcess Name : %s\n", g_szProcessname);
    if (g_szProcessPath == NULL)
    {
        printf_s("Can't get process path[Cann't load config file]!\nExit Program!");
        return -1;
    }

    snprintf(szConfigfilenameTemp, sizeof(szConfigfilenameTemp), "%s/%s/", g_szProcessPath, CONF_FILE_PATH);

    realpath(szConfigfilenameTemp, szConfigfilename);

    SafeStrCat(szConfigfilename, sizeof(szConfigfilename), "/", 1);
    SafeStrCat(szConfigfilename, sizeof(szConfigfilename), g_szProcessname, strnlen_s(g_szProcessname, sizeof(g_szProcessname)));
    SafeStrCat(szConfigfilename, sizeof(szConfigfilename), CONF_FILE_EXT, strnlen_s(CONF_FILE_EXT, sizeof(CONF_FILE_EXT)));

    printf_s("Process Name : %s\n", g_szProcessname);
    printf_s("Process Path : %s\n", g_szProcessPath);
    printf_s("Config Filename : %s\n", szConfigfilename);
#if 0
    while((options = getopt(argc, argv, "l:p:")) != EOF)
    {
        switch (options)
        {
             case 'l': /* 차로번호    */
                  nLane_no = atoi(optarg);
                  break;
             case 'p': /* 영업소ID    */
                  sprintf(plz_id, "%.2s", optarg);
                  break;
             default:  break;
        }
    }
#else
	sprintf(plz_id, "%.2s", argv[2]);
    nLane_no = lb_data2atoi(argv[4], 2);
#endif
proc_log("##### TAGBL PLZ_ID[%.2s] LANE[%02d]\n", plz_id, nLane_no);

    ReadConfigFile(true, szConfigfilename);

    if (InitLogConfig() != LOG_ERR_SUCCESS)
    {
        return DL_ERR_CONFIG;
    }

    if (InitProcessorMQConfig() != MQ_ERR_SUCCESS)
    {
        return DL_ERR_CONFIG;
    }

    if (InitThreadConfig() != THREAD_ERR_SUCCESS)
    {
        return DL_ERR_CONFIG;
    }

    return DL_ERR_SUCCESS;
}

void *WorkThread(void *pData)
{
    struct THREAD_INFO *pThreadInfo;
    char szMessageBuffer[MAX_STRING_SIZE + 1];
    int nResult;
    int *pnThreadExitCode;
    struct bl_struct *rd;
    char szCorrelationID[MAX_STRING_SIZE + 1];
    char szReplyQueuename[MAX_STRING_SIZE + 1];
    char szExchangername[MAX_STRING_SIZE + 1];
    int nMessageLength;
    uint64_t nDeliveryTag;

    pThreadInfo = (struct THREAD_INFO *)pData;
    pnThreadExitCode = NULL;
    nResult = SafeMemoryAlloc((void **)&pnThreadExitCode, sizeof(int));
    //pnThreadExitCode = SafeAlloc(pnThreadExitCode, sizeof(int));
    *pnThreadExitCode = 0;
/*
    while (pThreadInfo->bThreadLoop)
    {
*/
        if (pThreadInfo->sPublishMQ.bMQConnection == false || pThreadInfo->sPublishMQ.bMQChannelOpen == false
            || pThreadInfo->sConsumeMQ.bMQConnection == false || pThreadInfo->sConsumeMQ.bMQChannelOpen == false)
        {
            if (ConnectProcessorMQ(pThreadInfo, true) != MQ_ERR_SUCCESS)
            {
                WriteLog(LogType_StandardOut, LogLevel_Debug, "[Thread:%02d]ConnectProcessMQ is failed!", pThreadInfo->nThreadIndex);
				pThreadInfo->nRunState = SOCK_THREAD_STATE_TERMINATED;
				pthread_mutex_destroy(&pThreadInfo->sContextMutex);
				pthread_mutex_destroy(&pThreadInfo->sPublishMQ.sMQMutex);
				pthread_mutex_destroy(&pThreadInfo->sConsumeMQ.sMQMutex);
				SafeFree((void **)&pThreadInfo);
				SafeFree((void **)&pnThreadExitCode);
                return(-1);
            }
            WriteLog(LogType_StandardOut, LogLevel_Debug, "[Thread:%02d]ConnectProcessMQ is succeeded!!", pThreadInfo->nThreadIndex);
        }
proc_log("Reply Que[%s]\n", szReplyQueuename);
        //amqp_maybe_release_buffers(pThreadInfo->sMQConnectionState);
        nResult = GetMessageFromQueue(pThreadInfo->sConsumeMQ.sMQConnectionState, szExchangername, sizeof(szExchangername), szMessageBuffer, sizeof(szMessageBuffer), szCorrelationID, sizeof(szCorrelationID), szReplyQueuename, sizeof(szReplyQueuename), &pThreadInfo->sConsumeMQ.bMQConnection, &pThreadInfo->sConsumeMQ.bMQChannelOpen, &nDeliveryTag, NULL);

        nMessageLength = strnlen_s(szMessageBuffer, sizeof(szMessageBuffer));
proc_log("Back DB 처리 전[%d][%s][%s]\n", nResult, szMessageBuffer, szReplyQueuename);
        if (nResult == MQ_ERR_SUCCESS)
        {
            printf_s("Message Received : %s\n", szMessageBuffer);
            //WriteRawCommLog(LogType_CommOut, LogLevel_Info, pThreadInfo->nThreadIndex, 'C', "%s", szMessageBuffer);
            WriteQueueLog(LogType_MQOut, LogLevel_Info, pThreadInfo->nThreadIndex, 'C', g_szMQMessageRecvQueuename, "", szCorrelationID, nMessageLength, "%s", szMessageBuffer);
            WriteLog(LogType_StandardOut, LogLevel_Info, "[Thread:%02d]MQ Data Consume[Data:%s]!", pThreadInfo->nThreadIndex, szMessageBuffer);
            sprintf(retData, "%s", szMessageBuffer+45);
proc_log("Que 획득[%d][%s][%s]\n", nResult, szMessageBuffer+45, retData);
            rd = szMessageBuffer+45;

            //nResult = PutAckMessageToQueue(pThreadInfo->sMQConnectionState, szCorrelationID, szReplyQueuename, szMessageBuffer, strnlen_s(szMessageBuffer, sizeof(szMessageBuffer)), &pThreadInfo->bMQConnection, &pThreadInfo->bChannelOpen);
            amqp_basic_ack(pThreadInfo->sConsumeMQ.sMQConnectionState, 1, nDeliveryTag, 0);
            nResult = PutReplyMessageToQueue(pThreadInfo->sPublishMQ.sMQConnectionState, szCorrelationID, szReplyQueuename, szMessageBuffer, strnlen_s(szMessageBuffer, sizeof(szMessageBuffer)), &pThreadInfo->sPublishMQ.bMQConnection, &pThreadInfo->sPublishMQ.bMQChannelOpen);
proc_log("\n응답처리 결과[%d][%d]\nMessage[%s]\nReplyQue[%s]\n", nResult, strnlen_s(szMessageBuffer, sizeof(szMessageBuffer)), szMessageBuffer, szReplyQueuename);
            WriteQueueLog(LogType_MQOut, LogLevel_Info, pThreadInfo->nThreadIndex, 'P', "", szReplyQueuename, szCorrelationID, nMessageLength, "%s", szMessageBuffer);
            WriteLog(LogType_StandardOut, LogLevel_Info, "[Thread:%02d]Response Publish[Queue:%s,UUID:%s,Data:%s]!", pThreadInfo->nThreadIndex, szReplyQueuename, szCorrelationID, szMessageBuffer);
        }
        else
        {
            WriteLog(LogType_StandardOut, LogLevel_Debug, "[Thread:%02d]MQ Data Consume Error!", pThreadInfo->nThreadIndex);
        }
/*
    }
*/
    CloseMQ(pThreadInfo->nThreadIndex, pThreadInfo->sPublishMQ.sMQConnectionState, &pThreadInfo->sPublishMQ.bMQConnection, &pThreadInfo->sPublishMQ.bMQChannelOpen, &pThreadInfo->sPublishMQ.sMQMutex);
    CloseMQ(pThreadInfo->nThreadIndex, pThreadInfo->sConsumeMQ.sMQConnectionState, &pThreadInfo->sConsumeMQ.bMQConnection, &pThreadInfo->sConsumeMQ.bMQChannelOpen, &pThreadInfo->sConsumeMQ.sMQMutex);
	pThreadInfo->nRunState = SOCK_THREAD_STATE_TERMINATED;
	pthread_mutex_destroy(&pThreadInfo->sContextMutex);
    pthread_mutex_destroy(&pThreadInfo->sPublishMQ.sMQMutex);
    pthread_mutex_destroy(&pThreadInfo->sConsumeMQ.sMQMutex);
	SafeFree((void **)&pThreadInfo);
    SafeFree((void **)&pnThreadExitCode);
    return pnThreadExitCode;
}