
//---------------------------------------------------------------------------
#include "AppGlobalF.h"
#include "CommThread.h"
#include "DMCOMMF.h"
#include "FrmSysLogF.h"
#include "VmsPasigProtocolF.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------

//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall TCommThread::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------

/*
 * 스레드 생성자
 *  arguments
 *   void
 *  return
 *   void
 */
__fastcall TCommThread::TCommThread(bool CreateSuspended)
    : TThread(CreateSuspended)
{
    TCommThread();
}
//---------------------------------------------------------------------------

/*
 * 스레드 초기화
 *  arguments
 *   void
 *  return
 *   void
 */
__fastcall TCommThread::TCommThread(void)
    : TThread(true)
{
    Priority = tpNormal;
    FreeOnTerminate = true;
    Resume();
}
//---------------------------------------------------------------------------

/*
 * 스레드 소멸자
 *  arguments
 *   void
 *  return
 *   void
 */
__fastcall TCommThread::~TCommThread(void)
{

}
//---------------------------------------------------------------------------

/*
 * 스레드 실행
 *  arguments
 *   void
 *  return
 *   void
 */
void __fastcall TCommThread::Execute()
{
    MSG msg;
    int result;

    ::CoInitialize(NULL);

    NameThreadForDebugging("CommThread");

    while(!Terminated)
    {
        try
        {
            if (GetMessage(&msg, NULL, 0, 0) == 0)
            {
                Terminate();
            }
            else
            {
                result = SYS_ERR_NONE;

                try
                {
                    DisplayMsg(msg.message);

                    if (msg.message != WM_THREAD_TERMINATE)
                    {
                        if (!DMCOMM->DbConnect(g_AppCfg.db.sConnectStr))
                        {
                            result = SYS_ERR_DATABASE;
                        }
                    }
                    if (result == SYS_ERR_NONE)
                    {
                        switch (msg.message)
                        {
                        case WM_DATABASE_REFLASH:
                            //result = DMCOMM->GetDbSysdate();
                            break;
                        case WM_PROCESS_STATE:
                            result = DMCOMM->SaveProcessStateProc();
                            break;
                        case WM_EQUIP_STATE_ALL:
                            result = DMCOMM->SaveEquipStateAllProc();
                            break;
                        case WM_EQUIP_STATE:
                            result = DMCOMM->SaveEquipStateProc((TVmsCtlr*)msg.wParam, msg.lParam);
                            break;
                            break;
                        case WM_GET_ONOFF:
                            result = DMCOMM->LoadVmsOnOffTime();
                            //result = DMCOMM->GetVmsLuminanceTime();
                            break;
                        case WM_DOWNLOAD_PROC:
                            result = DMCOMM->GetVmsDownLoadInfo();
                            break;
                        case WM_MASTER_IMAGE_SYMBOL:
                        case WM_MASTER_IMAGE_TRAFFIC:
                            result = DMCOMM->GetVmsImage();
                            break;
                        case WM_MASTER_FORM:
                            result = DMCOMM->LoadVmsForm();
                            break;
                        case WM_MASTER_VMS_IFSC:
                            result = DMCOMM->GetVmsIfscInfo();
                            break;
                        case WM_DATA_SAVE:
                            //result = DMCOMM->DataSaveProc((void *)msg.wParam);
                            break;
                        case WM_PROVIDE_PROC:
                            result = DMCOMM->ProvideProc((void *)msg.wParam);
                            break;
                        case WM_SAVE_DOWNLOAD_FORM:
                            result = DMCOMM->SaveVmsDownloadForm();
                            break;
                        case WM_PROVIDE_SAVE:
                            result = DMCOMM->ProvideSave((void *)msg.wParam);
                            break;
                        case WM_THREAD_TERMINATE:
                            Terminate();
                            break;
                        }
                    }
                }
                catch(Exception &e)
                {
                    result = SYS_ERR_DATABASE;
                }

                if (msg.message == WM_PROVIDE_PROC)
                {
                    SendMessage((HWND)g_AppCfg.lMainWinHandle, WM_USER, WM_MAKE_DOWNLOAD_FORM, 0);
                }

                if (msg.message != WM_THREAD_TERMINATE)
                {
                    if (result == SYS_ERR_NONE)
                    {
                        DMCOMM->DbState(true);
                    }
                    else
                    {
                        DMCOMM->DbState(false);
                        LERROR("result error: [%X] %d", msg.message, result);
                    }
                    DMCOMM->DbClose();
                }
            }
        }
        catch(Exception &e)
        {
        }
    }

    if (g_SysInfo->State.hFinishEvent != NULL)
    {
        SetEvent(g_SysInfo->State.hFinishEvent);
    }

    ::CoUninitialize();
}
//---------------------------------------------------------------------------

void TCommThread::DisplayMsg(unsigned int AMsg)
{
    AnsiString sMsg = "";
    switch (AMsg)
    {
    case WM_DATABASE_REFLASH:       sMsg = "WM_DATABASE_REFLASH";               break;
    case WM_PROCESS_STATE:          sMsg = "WM_PROCESS_STATE";                  break;
    case WM_EQUIP_STATE_ALL:        sMsg = "WM_EQUIP_STATE_ALL";                break;
    case WM_EQUIP_STATE:            sMsg = "WM_EQUIP_STATE";                    break;
    case WM_MASTER_FORM:            sMsg = "WM_MASTER_FORM";                    break;
    case WM_MASTER_IMAGE_SYMBOL:    sMsg = "WM_MASTER_IMAGE_SYMBOL";            break;
    case WM_MASTER_IMAGE_TRAFFIC:   sMsg = "WM_MASTER_IMAGE_TRAFFIC";           break;
    case WM_MASTER_VMS_IFSC:        sMsg = "WM_MASTER_VMS_IFSC";                break;
    case WM_DATA_SAVE:              sMsg = "WM_DATA_SAVE";                      break;
    case WM_GET_ONOFF:              sMsg = "WM_GET_ONOFF";                      break;
    case WM_PROVIDE_PROC:           sMsg = "WM_PROVIDE_PROC";                   break;
    case WM_SAVE_DOWNLOAD_FORM:     sMsg = "WM_SAVE_DOWNLOAD_FORM";             break;
    case WM_PROVIDE_SAVE:           sMsg = "WM_PROVIDE_SAVE";                   break;
    case WM_DOWNLOAD_PROC:          sMsg = "WM_DOWNLOAD_PROC";                  break;
    case WM_THREAD_TERMINATE:       sMsg = "WM_THREAD_TERMINATE";               break;
    default:                        sMsg.printf("UNKNOWN MESSAGE: %02X", (BYTE)(AMsg-WM_USER));   break;
    }

    LDEBUG("%s", sMsg.c_str());
}
//---------------------------------------------------------------------------

int TCommThread::LogWrite(int ALogKind, char *AFmt, ...)
{
    va_list     ap;
    int         cnt = 0;
    char        szFmtData[MAX_LOG_BUFFER];
    AnsiString  sLogKind;
    int         nStep = 0;

    bool bLog = false;
    switch(ALogKind)
    {
    case eLOG_INFO   : bLog = g_LogCfg.Info;    sLogKind = " [INF] "; break;
    case eLOG_DATA   : bLog = g_LogCfg.Data;    sLogKind = " [DAT] "; break;
    case eLOG_ERROR  : bLog = g_LogCfg.Error;   sLogKind = " [ERR] "; break;
    case eLOG_WARNING: bLog = g_LogCfg.Warning; sLogKind = " [WAN] "; break;
    case eLOG_DEBUG  : bLog = g_LogCfg.Debug;   sLogKind = " [DBG] "; break;
    case eLOG_DETAIL : bLog = g_LogCfg.Detail;  sLogKind = " [DET] "; break;
    }
    if (!bLog) return -1;

    try
    {
        va_start(ap, AFmt);
        cnt = vsprintf(szFmtData, AFmt, ap);
        va_end(ap);

        nStep = 1;
        ITSLog->LogWrite(NULL, ALogKind, szFmtData);

        nStep = 2;
        //IPC_LOG_MESSAGE *pLog = new IPC_LOG_MESSAGE;
        IPC_LOG_MESSAGE *pLog = &FLogMsg;//(IPC_LOG_MESSAGE *)malloc(sizeof(IPC_LOG_MESSAGE));
        if (pLog)
        {
            pLog->Kind = ALogKind;
            pLog->Flag = 0;
            pLog->Len  = strlen(szFmtData);
            pLog->Tm   = Now();
            memset(pLog->Msg, 0x00, sizeof(pLog->Msg));
            sprintf(pLog->Msg, "%sTHRD %s", sLogKind.c_str(), szFmtData);

        	DWORD   dwResult = 0;
            LRESULT lResult = SEND_LOGMSG(FrmSysLog->Handle, WM_LOG_DISPLAY, pLog, NULL, SMTO_NORMAL, 2000, dwResult);
            if (lResult == 0)
            {
                dwResult = GetLastError();
                if (dwResult == ERROR_TIMEOUT)
                {
                }
                //SAFE_DELETE(pLog);
            }
        }
    }
    catch(Exception &e)
    {
        LERROR("LogWrite: %d", nStep);
    }
    return cnt;
}
//---------------------------------------------------------------------------


