//---------------------------------------------------------------------------

#include <vcl.h>
#include "FrmCommLogF.h"
#include "FrmSysLogF.h"
#include "VMSCommLibF.h"
#pragma hdrstop

#include "LogThreadF.h"

#pragma package(smart_init)

TLogThread *LogThread = NULL;
//---------------------------------------------------------------------------
TLogThread::TLogThread()
{
    FPnlState = NULL;
    FTmrDb = NULL;
}
//---------------------------------------------------------------------------
TLogThread::~TLogThread()
{
}
//---------------------------------------------------------------------------

void __fastcall TLogThread::updateLedColor(TColor AColor)
{
    try {
        if (FPnlState) {
            PostMessage((HWND)g_AppCfg.lMainWinHandle, WM_PANEL_REFRESH, 0, (LPARAM)AColor);
            //FPnlState->Color = AColor;
            //FPnlState->Refresh();
        }
    } catch(Exception &e) {}
}
//---------------------------------------------------------------------------

DWORD __fastcall TLogThread::Process(LPVOID AParam)
{
    IPC_LOG_MESSAGE *pLog;
    DWORD            dwJob;
    TMessage         Msg;

    MSG       qMsg;
    TITSLog  *pLogObj;
    TCDSCtlr *pCDSCtlr;

    while(!IsTerm() && !g_AppCfg.bThrExit)
    {
        updateLedColor(clGreen);

        if (!g_logQ.PopBlocking(dwJob))
        {
            continue;
        }
        if (dwJob == Q_CLOSE)
        {
            break;
        }
        else
        if (dwJob == Q_TICK)
        {
            updateLedColor(clRed);
            continue;
        }

        updateLedColor(clLime);

        pLog = (IPC_LOG_MESSAGE*)dwJob;
        Msg.WParam = (int)pLog;
        pLogObj = (TITSLog*)pLog->Obj;
        if (pLogObj && pLog->Write)
        {
            pLogObj->LogWrite(NULL, pLog->Kind, pLog->Msg);
        }

        try {
            if (pLog->Target == log_sys)
            {
                if (FrmSysLog) FrmSysLog->OnWMLogDisplayMessage(Msg);
                if (from_srvTcp == pLog->From || from_cliTcp == pLog->From)
                {
                    if (FrmCommLog)
                    {
                        if (FrmCommLog->Showing && FrmCommLog->CDSCtlr == (TCDSCtlr*)pLog->Ctlr) FrmCommLog->OnWMLogDisplayMessage(Msg);
                    }
                }
            }
            else
            if (pLog->Target == log_com)
            {
                pCDSCtlr = (TCDSCtlr*)pLog->Ctlr;
                if (pCDSCtlr && FrmCommLog)
                {
                    if (pCDSCtlr->FDispLog && FrmCommLog->Showing) FrmCommLog->OnWMLogDisplayMessage(Msg);
                }
            }
        }catch(Exception &e) {}

        //SAFE_DELETE(pLog);
    }

    Term();
    g_AppCfg.bThrJobExit = true;
    return 0;
}
//---------------------------------------------------------------------------

