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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "ITSLangTransF.h"
#include "ITSMapF.h"
#pragma hdrstop

#include "FrmCctvOprMainF.h"
#include "TThreadPollingF.h"
#include "FrmInitializeF.h"  // 프로그램 초기화화면

//---------------------------------------------------------------------------
#include "CTV0100MF.h"  // 정지영상 모니터링
#include "CTV0300MF.h"  // 상태 모니터링
#include "CTV0500MF.h"  // CCTV 제어

#include "CTVM100MF.h"  // 기본정보관리

//---------------------------------------------------------------------------
#ifndef ULONG_PTR
#define ULONG_PTR unsigned long *
#endif

#include <stdio.h>
#include <string.h>
#include <list>
#include <map>

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxHint"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "cxSpinEdit"
#pragma link "cxTextEdit"
#pragma link "dxBar"
#pragma link "dxCustomHint"
#pragma link "dxRibbon"
#pragma link "dxRibbonGallery"
#pragma link "dxRibbonSkins"
#pragma link "dxRibbonStatusBar"
#pragma link "dxScreenTip"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#pragma link "dxSkinChooserGallery"
#pragma link "dxSkinCoffee"
#pragma link "dxSkinDarkRoom"
#pragma link "dxSkinDarkSide"
#pragma link "dxSkinFoggy"
#pragma link "dxSkinGlassOceans"
#pragma link "dxSkiniMaginary"
#pragma link "dxSkinLilian"
#pragma link "dxSkinLiquidSky"
#pragma link "dxSkinLondonLiquidSky"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinMoneyTwins"
#pragma link "dxSkinOffice2007Black"
#pragma link "dxSkinOffice2007Blue"
#pragma link "dxSkinOffice2007Green"
#pragma link "dxSkinOffice2007Pink"
#pragma link "dxSkinOffice2007Silver"
#pragma link "dxSkinOffice2010Black"
#pragma link "dxSkinOffice2010Blue"
#pragma link "dxSkinOffice2010Silver"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinsdxBarPainter"
#pragma link "dxSkinsdxRibbonPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinsForm"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "dxStatusBar"
#pragma link "dxTabbedMDI"
#pragma link "IdAntiFreeze"
#pragma link "IdAntiFreezeBase"
#pragma link "IdBaseComponent"
#pragma resource "*.dfm"

TFrmCctvOprMain *FrmCctvOprMain = NULL;

#define MAX_EXEPROGRAM  5
ST_RUNPROGRAM  g_RunProgram[MAX_EXEPROGRAM+1] = {
    {"TFrmCctvLogStts",      "CctvLogStts.exe",   "CCTV상태이력조회"},
    {"TFrmCctvLogMsg",       "CctvLogMsg.exe",    "CCTV제공이력조회"},
    {"TFrmCctvLogCtl",       "CctvLogCtl.exe",    "CCTV제어이력조회"},
    {"TFrmCctvLogDnld",      "CctvLogDnld.exe",   "CCTV다운로드이력조회"},
    {"TFrmCctvCamViewer",    "CctvCamViewer.exe", "CCTV영상모니터링"},
    {"",                    "",                 ""},
};

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

__fastcall TFrmCctvOprMain::TFrmCctvOprMain(TComponent* Owner)
    : TdxCustomRibbonForm(Owner)//TdxCustomRibbonForm(Owner)//TForm(Owner)
{
    FLogoutTick = 0;

    DoubleBuffered = true;

    g_AppCfg.lMainWinHandle = (long)Handle;
    StartJobThread();
    while(!PostJobMessage(WM_THREAD, WP_PING)) ;

    Application->OnException = OnAppException;

    ::CoInitialize(NULL);

    //Caption = g_AppCfg.sTitle;

    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Initialize(Application, g_AppCfg.sLang, true, true);
	ITSSkin_Menu(this);

    String sCaption = "";
    ReadConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "CAPTION", sCaption);
    ITSSkin_Caption(sCaption == "1" ? true : false);

    BarVmsSys1->Visible = false;
    BarVmsMngr2->Visible = false;
    BarVmsMngr3->Visible = false;
    TabVmsFormMngr->Visible = false;
    TabVmsSchMngr->Visible = false;

    RVMSH200M->Visible = ivNever;
    RVMSH400M->Visible = ivNever;

    TabVmsConfig->Visible = false;
    NVMS0200M->Visible = ivNever;
    NVMSM300M->Visible = ivNever;       //VMS정보제공축관리
    NVMSM310M->Visible = ivNever;       //VMS정보제공축설정


    Ribbon->ShowTabGroups = true;  // 메뉴탭 show/hide
    Ribbon->QuickAccessToolbar->Visible = false;
    //Ribbon->ApplicationButton->Visible = false;
    Ribbon->SupportNonClientDrawing = true;
    Ribbon->EnableTabAero = true;

    TabVmsSystem->Active = true;

    SetColorScheme(g_AppCfg.sSkinName);
    //SetColorScheme("Blue");

    CMM_SetFormPosition(g_AppCfg.bSaveForm);
    CMM_LoadForm(g_sFormsDir, this);

    FCommServerState = vms_normal;

	TmrOnShow->Enabled = false;
    TmrAppState->Enabled = false;
}
//---------------------------------------------------------------------------

LONG __stdcall HelperExceptionFilter(struct _EXCEPTION_POINTERS * pContext)
{
    LONG  lRet  = EXCEPTION_EXECUTE_HANDLER;
    DWORD dwRet = ERROR_SUCCESS;

	__try
	{
        Application->NormalizeTopMosts();
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"시스템에서 알수없는 오류가 발생했습니다.\r\n프로그램을 다시 기동해 주세요.",
                                    L"시스템 오류", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"The system encountered an unknown error.\r\nPlease re-start the program.",
                                    L"System error", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        Application->RestoreTopMosts();
        //TerminateProcess(GetCurrentProcess(), 0);
	}
	__finally
	{
		if(ERROR_SUCCESS != dwRet)
		{
			lRet = EXCEPTION_CONTINUE_SEARCH;
		}
		exit(0);
	}
	return lRet;
}
//---------------------------------------------------------------------------

/*
 * Form이 메모리에서 생성될때 호출되는 생성자 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TFrmCctvOprMain::FormCreate(TObject *Sender)
{
    /* 레지스터리 등록 IE 최신버전 */
    String sExeName = ExtractFileName(Application->ExeName);
    ITSMap_Init(sExeName);
    //SetUnhandledExceptionFilter(HelperExceptionFilter);

    Application->ShowMainForm = false;

    try {
        Application->Icon->LoadFromResourceName(((unsigned int)HInstance), "MAINICON");
    } catch(...) { ShowMessage("LoadFromResourceName failed"); }

    //DeleteLogFiles((PTCHAR)g_sLogDir.c_str(), 30, (PTCHAR)"*.*");


    //WindowState = wsMaximized;

    // 종료조건이 있는경우..
    //Application->Terminate();
    //return;

    Application->ShowMainForm = true;
    Application->OnHint       = OnAppHint;

    ImgAlarm->Visible = false;
    ImgAlarmNormal->Visible = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::FormShow(TObject *Sender)
{
    Application->ProcessMessages();
    g_AppCfg.lMainWinHandle = (long)Handle;

    /*
    *  프로그램 초기화 작업
    */
    InitStatusBar();

	if (g_pLOGIN)
    {
        GetUserMenuRight(g_pLOGIN->sUserId, g_pLOGIN->sUserRightId);
    }

	TmrOnShow->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * 프로그램 기동후 최초에 수행된다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TFrmCctvOprMain::TmrOnShowTimer(TObject *Sender)
{
	TmrOnShow->Enabled = false;
	Application->ProcessMessages();

    //폴링작업 객체 초기화
    FPollTraffic.Cycle = (60*1000*2)+11;    // 정보제공구간소통정보
    FPollVmsMsg.Cycle  = (60*1000*2)+15;    // VMS Message

    FPollVmsState.Cycle  = (60*1000*2)+ 1;  // 시설물상태정보
    FPollPrcsState.Cycle = (60*1000*2)+ 3;  // 프로세스상태정보
    FPollIncident.Cycle  = (60*1000*2)+ 5;  // 돌발정보

    FPollTraffic.IsPolling = true;
    FPollVmsMsg.IsPolling  = true;

    FPollVmsState.IsPolling  = true;
    FPollPrcsState.IsPolling = true;
    FPollIncident.IsPolling  = true;

    TFrmInitialize *FrmInitialize = new TFrmInitialize(this);
    FrmInitialize->FThreadId = g_AppCfg.thr.dwThreadId;
    FrmInitialize->ShowModal();

    UpdateVmsCommStatus(true);

    int nPort = 4602;
    TItsProcess *pPrcs = ItsProcessManager->FLists.Find(g_AppCfg.sProcessId);
    if (!pPrcs)
    {
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"통신프로세스를 초기화 하지 못하였습니다.\r\n환경설정에서 시스템ID를 확인하세요.\r\n프로그램을 종료합니다.",
                                    L"프로그램 통신오류_1", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"Failed to initialize communication process.\r\nPlease check your system ID in preferences.\r\nExit the program.",
                                    L"Program communication error_1", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        g_AppCfg.bAppClose = true;
        Close();
        return;
    }

    nPort = pPrcs->PRGM_PORT.ToIntDef(4602);
    nPort += 1; //VMS운영단말은 DB에 저장되어 있지 않기 때문에 포트번호를 1 증가시켜 통신한다.
    int nResult = CComm_Initialize((long)Handle, g_AppCfg.sProcessId, "UOT", nPort, g_AppCfg.sLogDay);
    if (VERR_NONE != nResult)
    {
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"통신프로세스를 초기화 하지 못하였습니다.\r\n환경설정에서 시스템ID를 확인하세요.\r\n프로그램을 종료합니다.",
                                    L"프로그램 통신오류_1", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"Failed to initialize communication process.\r\nPlease check your system ID in preferences.\r\nExit the program.",
                                    L"Program communication error_1", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        g_AppCfg.bAppClose = true;
        Close();
        return;
    }
    FOR_STL(TItsProcess*, pObj, ItsProcessManager->FLists)
    {
        if (pObj->DEL_YN == "Y") continue;
        AnsiString sProcessId = AnsiString(pObj->SYST_ID);
        AnsiString sSystemTp  = AnsiString(pObj->SYST_TYPE);
        AnsiString sIpAddress = AnsiString(pObj->SYST_IP_1);
        AnsiString sUdpPort   = AnsiString(pObj->PRGM_PORT);
        if (CComm_AddProcess(sProcessId, sSystemTp, sIpAddress, sUdpPort) >= 0)
        {
            if ("UOT" == sSystemTp)
            {
                nPort = sUdpPort.ToIntDef(0);
                CComm_AddProcess(sProcessId, sSystemTp, sIpAddress, AnsiString(nPort+3));
            }
        }
    }
    if (VERR_NONE != CComm_Open())
    {
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"통신프로세스를 초기화 하지 못하였습니다.\r\n환경설정에서 시스템ID를 확인하세요.\r\n프로그램을 종료합니다.",
                                    L"프로그램 통신오류_3", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"Failed to initialize communication process.\r\nPlease check your system ID in preferences.\r\nExit the program.",
                                    L"Program communication error_3", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        g_AppCfg.bAppClose = true;
        Close();
        return;
    }

    UpdateInterCommStatus(true);

	Application->ProcessMessages();

    ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex = ITSDb_IsOpen() ? 8 : 7;

    //TODO NITS0000MClick((TObject *)NITS0000M);    //메인화면을 프로그램 기동과 동시에 호출하는 경우

#if 0
    if (g_AppCfg.AutoLogout.LogoutExit)
    {
        Application->MessageBox(L"이전 프로그램은 자동로그아웃으로 종료되었습니다.\r\n프로그램을 실행합니다.",
                                L"프로그램 실행정보", MB_OK|MB_ICONQUESTION|MB_APPLMODAL);
    }
#endif
    g_AppCfg.AutoLogout.LogoutExit = false;

    TmrAppState->Enabled = true;
    TmrPolling->Enabled = true;
    TmrCommTimeout->Enabled = true;

    INT_VMS_STATE_REQ Req;
    memset((char*)&Req, 0x00, sizeof(Req));
    Req.Count = 0;
    Req.Type  = vms_state_all;
    CComm_VmsStateReq(&Req);
}
//---------------------------------------------------------------------------

/*
 * 작업스레드 생성
 *  arguments
 *
 *  return
 *      void
 */
bool  __fastcall TFrmCctvOprMain::StartJobThread()
{
    TThreadPolling *pPollingThread = new TThreadPolling(false);
    if (pPollingThread)
    {
        pPollingThread->OnTerminate = OnPollingThreadDone;
        g_AppCfg.thr.pThread    = (TThread *)pPollingThread;
        g_AppCfg.thr.dwThreadId = pPollingThread->ThreadID;
        g_AppCfg.thr.nHandle    = pPollingThread->Handle;
        //pPollingThread->Resume();
        return true;
    }
    return false;
}
//---------------------------------------------------------------------------

/*
 * 작업스레드 종료
 *  arguments
 *
 *  return
 *      void
 */
void  __fastcall TFrmCctvOprMain::TerminateJobThread()
{
    if (g_AppCfg.thr.bRunning)
    {
        PostJobMessage(WM_THREAD, WM_QUIT);
    }
    
    Sleep(500);
    try
    {
        if (g_AppCfg.thr.bRunning)
        {
            TThreadPolling *pThread = (TThreadPolling *)g_AppCfg.thr.pThread;
            pThread->Terminate();
            //pThread->WaitFor();
        }
        g_AppCfg.thr.pThread    = NULL;
        g_AppCfg.thr.dwThreadId = 0;
        g_AppCfg.thr.nHandle    = 0;
        g_AppCfg.thr.bRunning   = false;
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

/*
 * Form이 닫히기 전에 프로그램의 종료여부를 확인한다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TFrmCctvOprMain::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    // 폼이 닫히기 전에 수행해야 할 모뮬 기술
    // 프로그램 종료를 사용자가 확인할 수 있도록...
	if (!g_AppCfg.bAppClose)
    {
#if 0
        String strMsg;
        strMsg = "";
        strMsg = "[ " + g_AppCfg.sTitle + " ]\r\n\n";
        strMsg+= FrmLang->cxLabel1->Caption;

		if(Application->MessageBox(strMsg.c_str(),
                                   FrmLang->cxLabel2->Caption.c_str(),
                                   MB_YESNO|MB_ICONQUESTION) == IDYES)
        {
            /*
            *  화면관련 작업을 못하도록 여기에 코드를 적자...
            */
            ITSDb_ApplicationTerm();
			g_AppCfg.bAppClose = true;
        }
#else
        ITSDb_ApplicationTerm();
        g_AppCfg.bAppClose = true;
#endif
        CanClose = false;
	}
}
//---------------------------------------------------------------------------

/*
 * Form을 닫을때 호출되는 event 메서드
 *  arguments
 *      Sender : event handler 객체
 *      Action : TCloseAction 객체
 *  return
 *      void
 */
void __fastcall TFrmCctvOprMain::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    Action = caFree;
}
//---------------------------------------------------------------------------

/*
 * 닫기버튼 이나 x버튼 클릭시 공통으로 처리하는 로직이들어간다..
 * Form과 DataModule class를 delete시킨다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TFrmCctvOprMain::CommClose()
{
    try
    {
        CComm_Close();

        CloseAllWindow();

        ITSSkin_Term();

        CMM_SaveForm(g_sFormsDir, this);

        WriteConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "LOGDAY", Now().FormatString("dd"));
        ::CoUninitialize();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

/*
 * 열려있는 모든 Form Window들을 닫는다.
 *  parameter
 *      Sender : Event를 보낸 객체
 *  return
 *      None
 */
void __fastcall TFrmCctvOprMain::CloseAllWindow()
{
    int ii;

    if (g_AppCfg.bTermChildProg)
    {
        // 실행시킨 프로그램을 종료시킨다.
        for (ii = 0; ii < MAX_EXEPROGRAM; ii++)
        {
            if (g_RunProgram[ii].AClassName == "")
                continue;

            TermItsProgram(g_RunProgram[ii].AClassName, "");
        }
    }

    //실행중인 화면을 종료 시킨다.
    try {
        for (ii = 0; ii < Screen->FormCount; ii++)
        {
            if (Screen->Forms[ii] != this)
            {
                if (::IsWindow(Screen->Forms[ii]->Handle))
                {
                    String sFormName = Screen->Forms[ii]->Name; 
                    if (sFormName == "ITSSkin") continue;
                    if (sFormName == "FrmSkin") continue;
                    if (sFormName == "FrmLang") continue;
                    if (sFormName.SubString(1, 11) == "PlugInChart") continue;

                    if (Screen->Forms[ii]->Owner == this ||
                        Screen->Forms[ii]->Owner == Application)
                    {
                        Screen->Forms[ii]->Close();
                        WaitForSingleObject(Screen->Forms[ii]->Handle, 500);
                    }
                }
            }
        }
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::CloseChildWindow()
{
    int ii;

    //실행중인 화면을 종료 시킨다.
    try {
        for (ii = 0; ii < Screen->FormCount; ii++)
        {
            if (Screen->Forms[ii] != this)
            {
                if (::IsWindow(Screen->Forms[ii]->Handle))
                {
                    String sFormName = Screen->Forms[ii]->Name;
                    if (sFormName == "ITSSkin") continue;
                    if (sFormName == "FrmSkin") continue;
                    if (sFormName == "FrmLang") continue;
                    if (sFormName.SubString(1, 11) == "PlugInChart") continue;

                    if (Screen->Forms[ii]->Owner == this ||
                        Screen->Forms[ii]->Owner == Application ||
                        Screen->Forms[ii]->FormStyle == fsMDIChild)
                    {
                        Screen->Forms[ii]->Close();
                        WaitForSingleObject(Screen->Forms[ii]->Handle, 500);
                    }
                }
            }
        }
    } catch(...) {}
}
//---------------------------------------------------------------------------

/*
 * 매1초 마다 주기적으로 실행되는 타이머
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TFrmCctvOprMain::TmrAppStateTimer(TObject *Sender)
{
    /*
    *  타이머가 1초간격으로 응용프로그램의 상태를 체크하고
    * 응용프로그램의 상태를 주기적으로 체크하여 필요한 조치를 수행한다.
    */
	if (g_AppCfg.bAppClose)
    {
        TmrAppState->Enabled = false;
        TmrPolling->Enabled = false;

        UserLogout(); // 로그아웃

        TerminateJobThread();

        ITSDb_Close();
        Close();                // 응용프로그램 종료
    }
    else
    {
        TmrAppState->Enabled = false;
        UpdateStatusBar();

        if (g_AppCfg.AutoLogout.Enabled)
        {
            FLogoutTick++;
            if (FLogoutTick > (g_AppCfg.AutoLogout.IntervalMin*60))
            {
                //자동로그아웃처리
                g_AppCfg.bAppClose = true;
                g_AppCfg.AutoLogout.LogoutExit = true;
            }
        }
        TmrAppState->Enabled = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::UpdateInterCommStatus(bool AOk)
{
    int nImgIdx = 8;
    if (AOk == false) nImgIdx = 7;
    if (((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbComm]->PanelStyle)->ImageIndex != nImgIdx)
    {
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbComm]->PanelStyle)->ImageIndex = nImgIdx;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::UpdateVmsCommStatus(bool ADb)
{
    if (ADb)
    {
        FOR_STL(TItsProcess*, pPrcs, ItsProcessManager->FLists)
        {
            if (pPrcs->SYST_TYPE == "VMS")
            {
                if (pPrcs->FCommStatus == "1")
                {
                    FCommServerState = vms_normal;
                }
                else
                {
                    FCommServerState = vms_error;
                }
                break;
            }
        }
    }

    int nImgIdx = 8;
    if (FCommServerState == vms_error) nImgIdx = 7;
    if (((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbVmsComm]->PanelStyle)->ImageIndex != nImgIdx)
    {
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbVmsComm]->PanelStyle)->ImageIndex = nImgIdx;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::UpdateStatusBar()
{
    try
    {
        dxStatusBar->Panels->Items[isbTime]->Text = Now().FormatString(STR_DATETIME);
#if 0
        if (ITSDb_IsOpen())
        {
            if (((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex != 8)
                ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex = 8;
        }
        else 
        {
            if (((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex != 7)
                ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex = 7;
        }
#endif
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::DebugMsg(String AMsg)
{
    dxStatusBar->Panels->Items[isbMsg]->Text = " " + AMsg;
    dxStatusBar->Panels->Items[isbMsg]->StatusBarControl->Refresh();    

    TmrDebugHide->Enabled = false;
    TmrDebugHide->Enabled = true;

    LOGINFO(AnsiString(AMsg).c_str());
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::TmrDebugHideTimer(TObject *Sender)
{
    dxStatusBar->Panels->Items[isbMsg]->Text = "";
    dxStatusBar->Panels->Items[isbMsg]->StatusBarControl->Refresh();    
    TmrDebugHide->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::InitStatusBar()
{
    try
    {
        dxStatusBar->Panels->Items[isbGisPos]->Text = "";
        dxStatusBar->Panels->Items[isbTime]->Text = Now().FormatString(STR_DATETIME);

        if (g_pLOGIN)
        {                                                          
            dxStatusBar->Panels->Items[isbUser]->Text = g_pLOGIN->sUserId;
            ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbUser]->PanelStyle)->ImageIndex = 9;
        }

        dxStatusBar->Panels->Items[isbHint]->Text = "";
        dxStatusBar->Panels->Items[isbMsg]->Text = "";
        
        UpdateStatusBar(); 
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFrmCctvOprMain::GetUserMenuRight(String AUserId, String AUserRight)
{
    String sQry;
    TADOQuery *pADO = NULL;
    try
    {
        sQry = "SELECT OPERSYST_MENU_ID                  \r\n"
               "  FROM TB_USER_GROP_MENU_ATHR            \r\n"
               " WHERE ATHR_YN = 'N'                     \r\n"
               "   AND GROP_ID = (SELECT GROP_ID         \r\n"
               "                    FROM TB_USER_INFR    \r\n"
               "                   WHERE USER_ID = :p01) \r\n";

        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", AUserId);
            ITSDb_SQLOpen(pADO);

            for( ; !pADO->Eof; pADO->Next())
            {
                String sMenuId = pADO->FieldByName("OPERSYST_MENU_ID")->AsString;

                try
                {
                    int nCompnentCnt = this->ComponentCount;
                    for (int ii = 0; ii < nCompnentCnt; ii++)
                    {
                        String sClassName = this->Components[ii]->ClassName();
                        if(sClassName == "TdxBarLargeButton")
                        {
                            TdxBarLargeButton *pMenu = (TdxBarLargeButton *)this->Components[ii];
                            if (pMenu->Name == sMenuId)
                            {
                                pMenu->Enabled = false;
                                break;
                            }
                        }
                    }
                }
                catch(...)
                {
                }
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("TFrmMain::GetUserMenuRight", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("TFrmMain::GetUserMenuRight", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
	}
	__finally
	{
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
	}
    return true;
}
//---------------------------------------------------------------------------

HWND __fastcall TFrmCctvOprMain::FindChildWindow(String sFormName)
{
    int nFormCnt = Screen->FormCount;
    for (int ii = 0; ii < nFormCnt; ii++)
    {
        TForm *pForm = Screen->Forms[ii];
        String sTmpFormName = pForm->Name.SubString(1, sFormName.Length());
        if (sTmpFormName == sFormName)
        {
            return pForm->Handle;
        }
    }

    return NULL;
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::OnSkinClick(TObject *Sender)
{
    TdxBarButton *pMenu = (TdxBarButton*)Sender;
    try {
        dxSkinController1->SkinName = pMenu->Caption;
        dxSkinController1->Refresh();
        //ITSSkin_SetName(dxSkinController1->SkinName);   
    } catch(...) {}
    
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::TmrPollingTimer(TObject *Sender)
{
    TmrPolling->Enabled = false;

    DWORD dwTick = GetTickCount();

    UpdateThreadStatus(true);   //작업스레드 실행 확인

    // 프로세스상태정보
    if (FPollPrcsState.IsPolling && FPollPrcsState.IsPollingTime(dwTick))
    {
        FPollPrcsState.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_00);
        DebugMsg(">>> Process Status Request");//">>> 프로세스 상태 조회 요청");
    }
    // VMS상태정보
    if (FPollVmsState.IsPolling && FPollVmsState.IsPollingTime(dwTick))
    {
        FPollVmsState.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_01);
        DebugMsg(">>> VMS Status Request");//">>> VMS 상태 조회 요청");
    }
    // VMS Message
    if (FPollVmsMsg.IsPolling && FPollVmsMsg.IsPollingTime(dwTick))
    {
        FPollVmsMsg.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_02);
        DebugMsg(">>> VMS Display Message Request");//">>> VMS 표출메시지 조회 요청");
    }
    // 소통정보
    if (FPollTraffic.IsPolling && FPollTraffic.IsPollingTime(dwTick))
    {
        SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
        FPollTraffic.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_03);
        DebugMsg(">>> Traffic Request");//">>> 소통정보 조회 요청");
    }
    // 돌발정보
    if (FPollIncident.IsPolling && FPollIncident.IsPollingTime(dwTick))
    {
        FPollIncident.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_05);
        DebugMsg(">>> Incident Request");//">>> 돌발정보 조회 요청");
    }

    if (!g_AppCfg.bAppClose) TmrPolling->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * 작업스레드로 작업 메시지를 전송한다.
 *  arguments
 *
 *  return
 *      void
 */
bool  __fastcall TFrmCctvOprMain::PostJobMessage(UINT nMsg, int WParam/*=0*/, int LParam/*=0*/)
{
    int nRes;
    
//if (g_AppCfg.bDebug) ITSUtil_Trace("PostJobMessage: Msg: %02X, WParam: %02X, LParam: %02X", nMsg, WParam, LParam);

    if (g_AppCfg.thr.dwThreadId)
    {
        for (int ii = 0; ii < 3; ii++)
        {
            if (PostThreadMessageW(g_AppCfg.thr.dwThreadId, nMsg, WParam, LParam))
            {
                nRes = 0;
                return true;
            }
            else
            {
                nRes = GetLastError();
                if (ERROR_INVALID_THREAD_ID == nRes) 
                {
                    Sleep(500);
                    continue;
                }
            }
        }
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::dxSkinChooserGalleryItem1SkinChanged(TObject *Sender, const UnicodeString ASkinName)
{
    g_AppCfg.sSkinName = ASkinName;

    WriteConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "SKINNAME", g_AppCfg.sSkinName);

    SetColorScheme(ASkinName);
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::SetColorScheme(String ASkinName)
{
    Ribbon->ColorSchemeName = ASkinName;

    dxSkinController1->SkinName = ASkinName;
    dxSkinController1->Refresh();

    dxTabbedMDIManager1->LookAndFeel->SkinName = ASkinName;
    dxStatusBar->Invalidate();
    //Panel1->Color = Ribbon->ColorScheme->GetPartColor(rfspRibbonForm);

    //Ribbon.ColorSchemeName := AName;
    //SkinChooserSelectSkinName(AName);
    //Panel1.Color := Ribbon.ColorScheme.GetPartColor(rfspRibbonForm);
    //dxStatusBar.Invalidate;
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::ExecuteItsProgram(String AClassName, String AExeName, String AOption)
{
	HWND hExeForm = FindWindow(AClassName.c_str(), NULL);
	if (hExeForm)
	{
		SetWindowPos(hExeForm, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
	}
	else
	{
        String sExeName = "";
        String sExeParam= "";
        //if (!ReadConfigInfo(g_AppCfg.sConfigFile, "PROGRAM", AOption, sExeName))
        {
            sExeName = AExeName;
            sExeParam= g_pLOGIN->sUserId;
        }
		ShellExecute(Handle, NULL, sExeName.c_str(), sExeParam.c_str(), NULL, SW_SHOWNORMAL);
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::TermItsProgram(String AClassName, String AExeName)
{
	HWND hExeForm = FindWindow(AClassName.c_str(), NULL);
	if (hExeForm)
	{
        POST_MSG(hExeForm, WM_CLOSE, 0, 0);
	}
}
//---------------------------------------------------------------------------

/*
 * EXE 프로그램 실행시킴
 */
void __fastcall TFrmCctvOprMain::OnRunProgramClick(TObject *Sender)
{
    TdxBarLargeButton *pButton = (TdxBarLargeButton*)Sender;
    int nIdx = pButton->Tag;

    if (nIdx < 0 || nIdx >= MAX_EXEPROGRAM)  return;
    if (g_RunProgram[nIdx].AClassName == "") return;

    ExecuteItsProgram(g_RunProgram[nIdx].AClassName, g_RunProgram[nIdx].AExeName, g_RunProgram[nIdx].AOption);
}
//---------------------------------------------------------------------------

/*
 * Application Hint Display Event Handler
 *  arguments
 *
 *  return
 *
 */
void __fastcall TFrmCctvOprMain::OnAppHint(TObject *Sender)
{
    dxStatusBar->Panels->Items[isbHint]->Text = " " + Application->Hint;
    dxStatusBar->Panels->Items[isbHint]->StatusBarControl->Refresh();
}
//---------------------------------------------------------------------------

/*
 * Application Exception Event Handler
 *  arguments
 *
 *  return
 *
 */
void __fastcall TFrmCctvOprMain::OnAppException(TObject *Sender, Exception *exception)
{
if (g_AppCfg.bDebug) ITSUtil_Trace("OnAppException");

    String sClassName = (NULL != Sender)        ? Sender->ClassName() : String("Unknown_Class");
    String sErrMsg    = (NULL != exception)     ? exception->Message  : String("Unknown_Error");
    String sError     = sClassName + " : " + sErrMsg;

    //Application->ShowException(&exception);

    Application->NormalizeTopMosts();
    Application->MessageBox(sError.c_str(), L"System Error", MB_OK|MB_ICONERROR|MB_APPLMODAL);
    Application->RestoreTopMosts();
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::UpdateThreadStatus(bool ARequest, bool APing/*=true*/)
{
return;
    try
    {
        if (APing) if (ARequest) PostJobMessage(WM_THREAD, WP_PING);
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbStatus]->PanelStyle)->ImageIndex =  ARequest ? 7 : 8;
        dxStatusBar->Panels->Items[isbDb]->StatusBarControl->Refresh();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::UpdateDbStatus(bool ASelect)
{
    try
    {
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex =  ASelect ? 7 : 8;
        dxStatusBar->Panels->Items[isbDb]->StatusBarControl->Refresh();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

/*
 * Application Event Message Handler
 *  arguments
 *
 *  return
 *
 */
void __fastcall TFrmCctvOprMain::ApplicationEvents1Message(tagMSG &Msg, bool &Handled)
{
    switch(Msg.message)
    {
    case WM_THREAD:
        switch(Msg.wParam)
        {
        case WP_PING:
            UpdateThreadStatus(false);  //스레드 핑 확인
            break;
        case WP_PARAM_TRAFFIC:
            break;
        case WP_DB_SELECT_START:
            UpdateDbStatus(true);
            break;
        case WP_DB_SELECT_OK:
        case WP_DB_SELECT_ERROR:
        case WP_DB_SELECT_CANCEL:
            UpdateDbStatus(false);
            if (Msg.wParam == WP_DB_SELECT_OK)
            {
                OnRefreshMessage(Msg.wParam, Msg.lParam);
            }
            break;
        }
        break;
    case WM_DATABASE_REFRESH:
        OnDatabaseMessage(Msg.wParam, Msg.lParam);
        break;
    case WM_PLUGINFORM:
        OnRefreshMessage(Msg.wParam, Msg.lParam);
        break;
    case WM_MOUSEMOVE:
    case WM_KEYDOWN:
    case WM_KEYUP:
        FLogoutTick = 0;
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::OnRefreshMessage(WPARAM AWParam, LPARAM ALParam)
{
    HWND hWnd;

    if (AWParam == WP_DB_SELECT_OK)
    {
        DWORD dwTick = GetTickCount();
        switch(ALParam)
        {
        case LP_MSG_00: DebugMsg("<<< Process Status Request Completed."/*"<<< 프로세스 상태 조회 완료"*/);       FPollPrcsState.Polling = dwTick; break;
        case LP_MSG_01: DebugMsg("<<< VMS Status Request Completed."/*"<<< VMS 상태 조회 완료"*/);                FPollVmsState.Polling  = dwTick; break;
        case LP_MSG_02: DebugMsg("<<< VMS Display Message Request Completed."/*"<<< VMS 표출메시지 조회 완료"*/); FPollVmsMsg.Polling    = dwTick; break;
        case LP_MSG_03: DebugMsg("<<< Traffic Request Completed."/*"<<< 소통정보 조회 완료"*/);                   FPollTraffic.Polling   = dwTick; break;
        case LP_MSG_05: DebugMsg("<<< Incident Request Completed."/*"<<< 돌발정보 조회 완료"*/);                  FPollIncident.Polling  = dwTick; break;
        }

        if (ALParam == LP_MSG_00)
        {
            UpdateVmsCommStatus(true);
        }
        else
        if (ALParam == LP_MSG_02)
        {
            RefreshVmsMessage(WM_VMS_FORM_REFRESH);
        }
        else
        if (ALParam == LP_MSG_05)
        {
            RefreshVmsMessage(WM_VMS_INCIDENT_REFRESH);
        }
        else
        {
            RefreshVmsMessage(WM_VMS_STATE_REFRESH);
        }

#if 0
        if (NVMS0000M->Enabled)
        {
            hWnd = FindChildWindow("VMS0000M");
            if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        }
#endif

#if 0
        if (ALParam == LP_MSG_11)
        {
            //시설물 상태정보 업데이트
            ShowFacilityStatus();
        }
#endif
    }
    else
    {
        LOGERROR("DB Thread failed: %02X[%02X]", ALParam, AWParam);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::OnDatabaseMessage(WPARAM AWParam, LPARAM ALParam)
{
#if 0
    HWND hWnd;

    switch(AWParam)
    {
    case WP_MSG_01: //소통등급변경
    case WP_MSG_02: //돌발정보변경(오보/등록/해제)
        if (NITS0000M->Enabled)
        {
            hWnd = FindChildWindow("ITS0000M");
            if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        }
        break;
    case WP_MSG_03: //시설물 정보 변경
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_14);
        //hWnd = FindChildWindow("ITS0000M");
        //if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        break;
    case WP_MSG_04: // IDB0070M-휴일정보
    case WP_MSG_05: // FrmLinkGradeSet-구간등급변경
    case WP_MSG_06: // IDB0060M - 소통등급
    case WP_MSG_07: // IDB0050M -교통파라미터
        //NodeLinkChangeReq(AnsiString("UTP01")); //통합교통정보가공시스템으로 정보변경 내용을 전송
        break;
    case WP_MSG_09: // IDB0100M
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_09); //작업스레드에서 읽어 처리하도록 한다.
        break;
    case WP_MSG_14: // DSRM010M -DSRC-RSE 관리
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_14); //작업스레드에서 읽어 처리하도록 한다.
        break;
    default:
        LOGERROR("Unknown Database Msg: %02X[%02X]", ALParam, AWParam);
        break;
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::OnUdpDataRecvMessage(TMessage &Msg)
{
    int             nResult;
    IPC_MSG_DATA   *RcvData = (IPC_MSG_DATA*)Msg.LParam;
    INT_SENDER     *Sender  = &RcvData->Sender;
    INT_PACKET     *Pkt     = &RcvData->Pkt;
    INT_HEAD       *head    = &Pkt->head;
    INT_DATA       *data    = &Pkt->data;
    char           *pData   = &Pkt->Data[0];
    BYTE            OpCode  = head->OPCode;

    LOGINFO("*** OPR Client Req: %s.%d", CComm_ulong2ip(Sender->IP), Sender->Port);

    String sMsg     = "";
    String sVmsNmbr = "";

    TmrCommTimeout->Enabled = false;

    //FCommServerState = vms_normal;

    UpdateVmsCommStatus(false);
    UpdateInterCommStatus(true);

    switch(OpCode)
    {
    case INT_OP_PG_STATE_RES:
        {
            DebugMsg("*** VMS Process Stauts Recvieved");//"*** VMS 프로세스 상태정보 수신");
            INT_PG_STATE_RES *ARes = (INT_PG_STATE_RES*)pData;
            for (int ii = 0; ii < ARes->Count && ii < INT_MAX_PG_STATE; ii++)
            {
                if (ARes->Unit[ii].Type == INT_ID_VMS_SERVER)
                {
                    FCommServerState = ARes->Unit[ii].Action;
                    UpdateVmsCommStatus(false);
                    FPollPrcsState.Polling = GetTickCount();  //프로세스상태정보 조회 타이머 리셋
                    break;
                }
            }
        }
        break;
    case INT_OP_VMS_STATE_RES:
        {
#if 0
            char szVmsNmbr[INT_VMS_MAX_ID+1];
            INT_VMS_STATE_RES *ARes = (INT_VMS_STATE_RES*)pData;

            sMsg = "";
            //sMsg.printf(L"*** VMS 제어기 상태정보 수신: %d EA", ARes->Count);
            sMsg.printf(L"*** VMS Controller Status Received: %d EA", ARes->Count);
            DebugMsg(sMsg);

            for (int ii = 0; ii < ARes->Count && ii < INT_MAX_VMS_STATE; ii++)
            {
                sMsg = "";
                String sVmsNmbr;
                INT_VMS_STATE *pVms = &ARes->Unit[ii];
                sprintf(szVmsNmbr, "%.*s", INT_VMS_MAX_ID, (char*)pVms->VmsId);
                sVmsNmbr = String(szVmsNmbr);
                TVmsCtlr *pObj = VmsManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    VmsStatusCopy(&pObj->WSTATE, pVms);
                    if      (pObj->WSTATE.OprMode == 'A') pObj->OPER_MODE = "A";
                    else if (pObj->WSTATE.OprMode == 'B') pObj->OPER_MODE = "B";
                    else                                  pObj->OPER_MODE = "F";

                    //pObj->VMS_PHSE_CHNG_CYCL    = pObj->WSTATE.ScheduledMessageOperatingTime;
                    pObj->VMS_CMNC_ERR_BASS_VAL = pObj->WSTATE.ModuleOperatingTemperature;
                    pObj->FAN_MTNS_TMPR         = pObj->WSTATE.FanOperatingTemperature;
                    pObj->HETR_MTNS_TMPR        = pObj->WSTATE.HeaterOperatingTemperature;
                    pObj->VMS_MODL_ERR_RATE     = pObj->WSTATE.ModuleBasicFailureRate;

                    pObj->CheckRunState();

                    if (pObj->WSTATE.Comm != vms_normal)
                    {
                        pObj->VmsMsg->OFFER_YN = false;
                    }
                }
                else
                {
                    sMsg.printf(L"INT_OP_VMS_STATE_RES VMS not found: %s", sVmsNmbr.c_str());
                    DebugMsg(sMsg);
                }
            }
            RefreshVmsMessage(WM_VMS_STATE_REFRESH);

            FPollVmsState.Polling = GetTickCount();
#endif
        }
        break;
    case INT_OP_VMS_FORM_SAVE:
        {
            FPollVmsMsg.Reset();    //VMS메시지 조회 타이머 리셋

            char szDateTime[INT_VMS_MAX_DATETIME+1];
            INT_VMS_FORM_SAVE_REQ *AReq = (INT_VMS_FORM_SAVE_REQ*)pData;

            sprintf(szDateTime, "%.*s", INT_VMS_MAX_DATETIME, (char*)AReq->Date);

            String sDateTime = String(szDateTime);

            sMsg = "";
            //sMsg.printf(L"*** VMS 폼생성 완료 메시지 수신: %s", sDateTime.c_str());
            sMsg.printf(L"*** VMS Form Create Message Received: %s", sDateTime.c_str());
            DebugMsg(sMsg);
        }
        break;
    }
    TmrCommTimeout->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::RefreshVmsMessage(int AMsg, WPARAM AWParam/*=0*/, LPARAM ALParam/*=0*/)
{
    HWND hWnd;

    if (NVMS0000M->Enabled)
    {
        hWnd = FindChildWindow("VMS0000M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
    if (NCTV0100M->Enabled)
    {
        hWnd = FindChildWindow("CTV0100M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
    if (NVMS0200M->Enabled)
    {
        hWnd = FindChildWindow("VMS0200M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
    if (NCTV0300M->Enabled)
    {
        hWnd = FindChildWindow("CTV0300M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
#if 0
    if (NVMS0400M->Enabled)
    {
        hWnd = FindChildWindow("VMS0400M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
#endif
    if (NCTV0500M->Enabled)
    {
        hWnd = FindChildWindow("CTV0500M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
    if (NVMS0600M->Enabled)
    {
        hWnd = FindChildWindow("VMS0600M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::OnPollingThreadDone(TObject *Sender)
{
    LOGINFO("*** Polling thead terminated ***");
    g_AppCfg.thr.bRunning = false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::ShowFacilityStatus()
{
//    HWND hWnd = FindChildWindow("ITS0000M");
//    if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
return;

#if 0
    bool bShow = false;
    try
    {
        try
        {
            ItsFacilityManager->FLists.Lock();
            FOR_STL(TItsFacility*, pFacility, ItsFacilityManager->FLists)
            {
                if (pFacility->DEL_YN == "Y") continue;

                if (pFacility->FCLT_TYPE == "DSRC")
                {
                    if (pFacility->FCollCntBase > pFacility->FCollCntCurr)
                    {
                        bShow = true;
                        break;
                    }
                }

                if (pFacility->FComm != "1")
                {
                    bShow = true;
                    break;
                }
                else
                {
                    try
                    {
                        String sValue = pFacility->FCBoxTmpr;
                        int nValue = 0;
                        if (TryStrToInt(sValue, nValue))
                        {
                            if (nValue > g_AppCfg.Temp.AlarmValue)
                            {
                                bShow = true;
                                break;
                            }
                        }
                    } catch(...) {}
                }
            }
        }
        __finally
        {
            ItsFacilityManager->FLists.UnLock();
        }
    }
    catch(...)
    {
    }

    if (!bShow)
    {
        LblAlarm->Style->Font->Color = clBlack;
        LblAlarm->Caption = "알람정보";
        ImgAlarm->Visible = false;
        ImgAlarmNormal->Visible = true;
        try {
            if (ImgAlarm->Picture->Graphic->ClassName() == "TGIFImage")
                ((TGIFImage *)ImgAlarm->Picture->Graphic)->Animate = false;
        } catch(...) {}
        return;
    }

    ImgAlarmNormal->Visible = false;
    ImgAlarm->Visible = true;
    try {
        if (ImgAlarm->Picture->Graphic->ClassName() == "TGIFImage")
            ((TGIFImage *)ImgAlarm->Picture->Graphic)->Animate = true;
    } catch(...) {}
    LblAlarm->Caption = "알람발생";
    LblAlarm->Style->Font->Color = clRed;

    if (!g_AppCfg.Alarm.Enabled) return;
    if (!g_AppCfg.Alarm.Window) return;
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::NTST0000MClick(TObject *Sender)
{
#if 0
    String sExeName = "Project1.exe";
    String sParam   = "\"" + g_pLOGIN->sUserId + "\" \"" + g_pLOGIN->sUserId + "\"";
    //ShellExecute(NULL,"open", "C:\\myprocess.exe", "\"my argument 1 containing spaces\" \"my argument 2\"","C:\\",SW_SHOWNORMAL);

    ShellExecute(Handle, NULL, sExeName.c_str(), sParam.c_str(), NULL, SW_SHOWNORMAL);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::NCTV0100MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(CTV0100M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::NCTV0300MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(CTV0300M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::NCTV0500MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(CTV0500M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::TmrCommTimeoutTimer(TObject *Sender)
{
    //통신타임아웃
    TmrCommTimeout->Enabled = false;
    UpdateInterCommStatus(false);
    FCommServerState = vms_error;
    UpdateVmsCommStatus(false);
    LOGINFO("xxx VMS Communication Time out xxx");
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::ApplicationEvents1Restore(TObject *Sender)
{
    //화면 재생
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::ApplicationEvents1Minimize(TObject *Sender)
{
    //화면 정지
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::OnMenuMouseMove(TObject *Sender, TShiftState Shift, int X,
          int Y)
{
    ::SetCursor(Screen->Cursors[crHandPoint]);
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::ApplicationEvents1SettingChange(TObject *Sender, int Flag,
          const UnicodeString Section, int &Result)
{
    DateSeparator = '-';
    TimeSeparator = ':';
    ShortDateFormat = "yyyy-MM-dd";
    ShortTimeFormat = "HH:NN:SS";
    LongTimeFormat  = "HH:NN:SS";

    cxFormatController()->BeginUpdate();
    cxFormatController()->UseDelphiDateTimeFormats = true;
    cxFormatController()->EndUpdate();
    cxFormatController()->GetFormats();
    cxFormatController()->NotifyListeners();
}
//---------------------------------------------------------------------------

void __fastcall TFrmCctvOprMain::NCTVM100MClick(TObject *Sender)
{
    FORMSHOW(CTVM100M);
}
//---------------------------------------------------------------------------

