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

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

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

//---------------------------------------------------------------------------
#include "VMS0500MF.h"
#include "VMS0100MF.h"
#include "VMS0200MF.h"
#include "VMS0300MF.h"
#include "VMS0600MF.h"
#include "VMS0000MF.h"
#include "VMS0010MF.h"

#include "VMSM100MF.h"
#include "VMSM200MF.h"
#include "VMSM210MF.h"

#include "VMSM400MF.h"
#include "VMSM410MF.h"
#include "VMSM420MF.h"
#include "VMSM430MF.h"

#include "VMSM500MF.h"

#include "VMSM600MF.h"
#include "VMSM700MF.h"
#include "VMSM800MF.h"
#include "VMSM900MF.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#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"

TFrmVmsOprMain *FrmVmsOprMain = NULL;

#define MAX_EXEPROGRAM  5
ST_RUNPROGRAM  g_RunProgram[MAX_EXEPROGRAM+1] = {
    {"TFrmVmsLogStts",      "VmsLogStts.exe",   "VMS상태이력조회"},
    {"TFrmVmsLogDspl",      "VmsLogDspl.exe",   "VMS제공이력조회"},
    {"TFrmVmsLogCtrl",      "VmsLogCtrl.exe",   "VMS제어이력조회"},
    {"TFrmVmsLogDnld",      "VmsLogDnld.exe",   "VMS다운로드이력조회"},
    {"TFrmVmsCamViewer",    "VmsCamViewer.exe", "VMS영상모니터링"},
    {"",                    "",                 ""},
};

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

__fastcall TFrmVmsOprMain::TFrmVmsOprMain(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;
    BarVmsSchMngr4->Visible = false;
    //NVMSM900M->Visible = ivNever;

    NVMSM800M->Visible = ivNever;   //VMS기본스케쥴'
    BarVmsSchMngr3->Visible = false;

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

    NVMS0600M->Visible = ivNever;       //모듈상태 모니터링

    NVMS0TEST->Visible = ivNever;
    NVMSM430M->Visible = ivNever;

    NVMS0010M->Visible = ivNever;  //정보제공구간 현재소통정보
    NVMSM420M->Visible = ivNever;  //소통정보 이미지 관리

    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);

    FVmsServerState = vms_comm_normal;

    APP_InitDisplayColor();

	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;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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 TFrmVmsOprMain::FormShow(TObject *Sender)
{
    Application->ProcessMessages();
    g_AppCfg.lMainWinHandle = (long)Handle;

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

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

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

void __fastcall TFrmVmsOprMain::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+1));
            }
        }
    }
    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_req_state_all;
    CComm_VmsStateReq(&Req);
}
//---------------------------------------------------------------------------

bool  __fastcall TFrmVmsOprMain::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;
}
//---------------------------------------------------------------------------

void  __fastcall TFrmVmsOprMain::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(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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
        CloseAllWindow();

        ITSDb_ApplicationTerm();
        g_AppCfg.bAppClose = true;
#endif
        CanClose = false;
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    Action = caFree;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::CommClose()
{
    try
    {
        CComm_Close();

        //CloseAllWindow();

        ITSSkin_Term();

        CMM_SaveForm(g_sFormsDir, this);

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

void __fastcall TFrmVmsOprMain::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();
                        PostMessage(Screen->Forms[ii]->Handle, WM_CLOSE, 0, 0);
                        WaitForSingleObject(Screen->Forms[ii]->Handle, 1000);
                    }
                }
            }
        }
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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 TFrmVmsOprMain::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 TFrmVmsOprMain::UpdateVmsCommStatus(bool ADb)
{
    if (ADb)
    {
        FOR_STL(TItsProcess*, pPrcs, ItsProcessManager->FLists)
        {
            if (pPrcs->SYST_TYPE == "VMS")
            {
                if (pPrcs->FCommStatus == "1")
                {
                    FVmsServerState = vms_comm_normal;
                }
                else
                {
                    FVmsServerState = vms_comm_error;
                }
                break;
            }
        }
    }

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

void __fastcall TFrmVmsOprMain::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 TFrmVmsOprMain::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 TFrmVmsOprMain::TmrDebugHideTimer(TObject *Sender)
{
    dxStatusBar->Panels->Items[isbMsg]->Text = "";
    dxStatusBar->Panels->Items[isbMsg]->StatusBarControl->Refresh();    
    TmrDebugHide->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::InitUserMenu()
{
    NVMS0100M->Enabled = false; //현시 모니터링
    NVMS0200M->Enabled = false; //시나리오 모니터링
    NVMS0300M->Enabled = false; //상태 모니터링
    NVMS0400M->Enabled = false; //영상 모니터링[R]
    NVMS0500M->Enabled = false; //VMS 제어
    NVMSM100M->Enabled = false; //기본정보 관리
    NVMSM200M->Enabled = false; //정보제공구간 관리
    NVMSM210M->Enabled = false; //정보제공구간 설정
    NVMSM400M->Enabled = false; //심볼이미지 관리
    NVMSM410M->Enabled = false; //소통정보 배경이미지 관리
    NVMSM500M->Enabled = false; //VMS 폼관리
    NVMSM600M->Enabled = false; //자동 스케줄 관리
    NVMSM700M->Enabled = false; //고정 스케줄 관리
    NVMSM800M->Enabled = false; //기본 스케줄 관리
    RVMSH100M->Enabled = false; //상태 이력조회[R]
    RVMSH200M->Enabled = false; //제공 이력조회[R]
    RVMSH300M->Enabled = false; //제어 이력조회[R]
}
//---------------------------------------------------------------------------
void __fastcall TFrmVmsOprMain::SetUserMenu(String AMenuId)
{
    String sMenuId = "";

    if      (AMenuId == "MS000000") sMenuId = "";           //VMS관리프로그램 ==> 이거는 기존거 그냥 이용... 메뉴처리 없음
    else if (AMenuId == "MS010000") sMenuId = "NVMS0100M";  //, '현시 모니터링'
    else if (AMenuId == "MS010100") sMenuId = "NVMS0200M";  //, '시나리오 모니터링'
    else if (AMenuId == "MS010101") sMenuId = "NVMS0300M";  //, '상태 모니터링'
    else if (AMenuId == "MS010102") sMenuId = "NVMS0400M";  //, '영상 모니터링[R]'
    else if (AMenuId == "MS010103") sMenuId = "NVMS0500M";  //, 'VMS 제어'
    else if (AMenuId == "MS010104") sMenuId = "NVMSM100M";  //, '기본정보 관리'
    else if (AMenuId == "MS010200") sMenuId = "NVMSM200M";  //, '정보제공구간 관리'
    else if (AMenuId == "MS010201") sMenuId = "NVMSM210M";  //, '정보제공구간 설정'
    else if (AMenuId == "MS010202") sMenuId = "NVMSM400M";  //, '심볼이미지 관리'
    else if (AMenuId == "MS010300") sMenuId = "NVMSM410M";  //, '소통정보 배경이미지 관리'
    else if (AMenuId == "MS010301") sMenuId = "NVMSM500M";  //, 'VMS 폼관리'
    else if (AMenuId == "MS010302") sMenuId = "NVMSM600M";  //, '자동 스케줄 관리'
    else if (AMenuId == "MS010303") sMenuId = "NVMSM700M";  //, '고정 스케줄 관리'
    else if (AMenuId == "MS020000") sMenuId = "NVMSM800M";  //, '기본 스케줄 관리'
    else if (AMenuId == "MS020100") sMenuId = "RVMSH100M";  //, '상태 이력조회[R]'
    else if (AMenuId == "MS020101") sMenuId = "RVMSH200M";  //, '제공 이력조회[R]'
    else if (AMenuId == "MS020102") sMenuId = "RVMSH300M";  //, '제어 이력조회[R]'

    if (sMenuId == "") return;
    TdxBarLargeButton *pMenu = (TdxBarLargeButton *)FindComponent(sMenuId);
    if (pMenu)
    {
        pMenu->Enabled = true;
        if (sMenuId == "NVMS0500M") g_bControlAuth = false; //VMS제어 화면에 대한 권한이 있으면 다른 제어권한 설정
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFrmVmsOprMain::GetUserMenuRight(String AUserId, String AUserRight)
{
    //평택은 기존에 메뉴정보를 가지고 있어서 다르게 처리한다.
    //모든 메뉴 비활성화, 디비에 등록된 메뉴 활성화
    InitUserMenu();

    String sQry;
    TADOQuery *pADO = NULL;
    try
    {
        sQry = "SELECT MENUID           \r\n"
               "  FROM OPERAUTH_MENU    \r\n"
               " WHERE OPERAUTH = :p01  \r\n";

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

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

            for( ; !pADO->Eof; pADO->Next())
            {
                String sMenuId = pADO->FieldByName("MENUID")->AsString;
                SetUserMenu(sMenuId);
#if 0
                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(...)
                {
                }
#endif
            }
        }
        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 TFrmVmsOprMain::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 TFrmVmsOprMain::OnSkinClick(TObject *Sender)
{
    TdxBarButton *pMenu = (TdxBarButton*)Sender;
    try {
        dxSkinController1->SkinName = pMenu->Caption;
        dxSkinController1->Refresh();
        //ITSSkin_SetName(dxSkinController1->SkinName);   
    } catch(...) {}
    
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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_PROCESS_STTS);
        DebugMsg(">>> Process Status Request");//">>> 프로세스 상태 조회 요청");
    }
    // VMS상태정보
    if (FPollVmsState.IsPolling && FPollVmsState.IsPollingTime(dwTick))
    {
        FPollVmsState.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_FACILITY_STTS);
        DebugMsg(">>> VMS Status Request");//">>> VMS 상태 조회 요청");
    }
    // VMS Message
    if (FPollVmsMsg.IsPolling && FPollVmsMsg.IsPollingTime(dwTick))
    {
        FPollVmsMsg.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_VMS_DSPLMSG);
        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_TRAFFIC);
        DebugMsg(">>> Traffic Request");//">>> 소통정보 조회 요청");
    }
    // 돌발정보
    if (FPollIncident.IsPolling && FPollIncident.IsPollingTime(dwTick))
    {
        FPollIncident.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_INCIDENT);
        DebugMsg(">>> Incident Request");//">>> 돌발정보 조회 요청");
    }

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

bool  __fastcall TFrmVmsOprMain::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 TFrmVmsOprMain::dxSkinChooserGalleryItem1SkinChanged(TObject *Sender, const UnicodeString ASkinName)
{
    g_AppCfg.sSkinName = ASkinName;

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

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

void __fastcall TFrmVmsOprMain::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 TFrmVmsOprMain::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 TFrmVmsOprMain::TermItsProgram(String AClassName, String AExeName)
{
	HWND hExeForm = FindWindow(AClassName.c_str(), NULL);
	if (hExeForm)
	{
        POST_MSG(hExeForm, WM_CLOSE, 0, 0);
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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);
}
//---------------------------------------------------------------------------

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

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

void __fastcall TFrmVmsOprMain::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:
        FLogoutTick = 0;
        break;
    case WM_KEYDOWN:
        FLogoutTick = 0;
        if (Msg.wParam == VK_F5)
        {
//            Handled = true;
        }
        break;
    case WM_KEYUP:
        FLogoutTick = 0;
        break;
    }
}
//---------------------------------------------------------------------------

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

    // 폴링 스레드에서 데이터작업 완료 메시지 처리
    if (AWParam == WP_DB_SELECT_OK)
    {
        DWORD dwTick = GetTickCount();
        switch(ALParam)
        {
        case LP_MSG_PROCESS_STTS:  DebugMsg("<<< Process Status Request Completed."/*"<<< 프로세스 상태 조회 완료"*/);       FPollPrcsState.Polling = dwTick; break;
        case LP_MSG_FACILITY_STTS: DebugMsg("<<< VMS Status Request Completed."/*"<<< VMS 상태 조회 완료"*/);                FPollVmsState.Polling  = dwTick; break;
        case LP_MSG_VMS_DSPLMSG:   DebugMsg("<<< VMS Display Message Request Completed."/*"<<< VMS 표출메시지 조회 완료"*/); FPollVmsMsg.Polling    = dwTick; break;
        case LP_MSG_TRAFFIC:       DebugMsg("<<< Traffic Request Completed."/*"<<< 소통정보 조회 완료"*/);                   FPollTraffic.Polling   = dwTick; break;
        case LP_MSG_INCIDENT:      DebugMsg("<<< Incident Request Completed."/*"<<< 돌발정보 조회 완료"*/);                  FPollIncident.Polling  = dwTick; break;
        }

        if (ALParam == LP_MSG_PROCESS_STTS)
        {
            UpdateVmsCommStatus(true);
        }
        else
        if (ALParam == LP_MSG_VMS_DSPLMSG)
        {
            RefreshVmsMessage(WM_VMS_FORM_REFRESH);
        }
        else
        if (ALParam == LP_MSG_INCIDENT)
        {
            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 (ALParam == LP_MSG_TRAFFIC)
        {
            hWnd = FindChildWindow("VMS0010M");
            if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        }

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

void __fastcall TFrmVmsOprMain::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 TFrmVmsOprMain::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.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;

    //FVmsServerState = vms_comm_normal;

    UpdateVmsCommStatus(false);
    UpdateInterCommStatus(true);

    switch(OpCode)
    {
    case INT_OP_TRAFFIC_CHANGE:       	/* 0x01, 교통정보가공완료 */
        {
            DebugMsg("*** Traffic Changed");
            FPollTraffic.Reset(); // 링크소통정보(전체)
        }
        break;
    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)
                {
                    FVmsServerState = ARes->Unit[ii].Action;
                    UpdateVmsCommStatus(false);
                    FPollPrcsState.Polling = GetTickCount();  //프로세스상태정보 조회 타이머 리셋
                    break;
                }
            }
        }
        break;
    case INT_OP_VMS_PARAM_RES:
        {
            INT_VMS_PARAM_RES *ARes = (INT_VMS_PARAM_RES*)pData;

            sMsg = "";
            sMsg.printf(L"*** VMS Controller Parameter Received: %d EA", ARes->Count);
            DebugMsg(sMsg);

            for (int ii = 0; ii < ARes->Count && ii < INT_VMS_MAX_PARAM; ii++)
            {
                INT_VMS_PARAM *pVms = &ARes->Unit[ii];
                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(String(pVms->VMS_CTLR_NMBR));
                if (pObj)
                {
                    pObj->PANL_PWER_MODE = pVms->led;     //	N	NUMBER(3)	Y	2		전광판 전원 모드(0x00:꺼짐,0x01:켜짐,0x02:자동,0x09:알수없음)
                    pObj->FAN_MODE       = pVms->fan;           //	N	NUMBER(3)	Y	2		FAN 동작모드(0x00:꺼짐,0x01:켜짐,0x02:자동,0x09:알수없음)
                    pObj->FAN_RUN_TMPR   = pVms->fanTmpr;       //	N	NUMBER(3)	Y	30		팬 동작 온도
                    pObj->HETR_MODE      = pVms->hetr;          //	N	NUMBER(3)	Y	2		히터 동작모드(0x00:꺼짐,0x01:켜짐,0x02:자동,0x09:알수없음)
                    pObj->HETR_RUN_TMPR  = pVms->hetrTmpr;      //	N	NUMBER(3)	Y	0		히터 동작 온도
                    pObj->BRGH_MODE      = pVms->brgh;          //	N	NUMBER(3)	Y	2		휘도 모드(0x00:주간,0x01:야간,0x00:자동,0x09:알수없음)
                    pObj->BRGH_CURR_STEP = pVms->brghVal;     //	N	NUMBER(3)	Y	40		휘도 현재 단계(0~100)
                    pObj->BRGH_WEEK_STEP = pVms->brghDay;     //	N	NUMBER(3)	Y	64		휘도 주간 단계(0~100)
                    pObj->BRGH_NGHT_STEP = pVms->brghNight;     //	N	NUMBER(3)	Y	48		휘도 야간 단계(0~100)
                    pObj->ParamResTime.printf(L"%s", pVms->time);
                }
                else
                {
                    sMsg.printf(L"INT_OP_VMS_PARAM_RES VMS not found: %s", String(pVms->VMS_CTLR_NMBR).c_str());
                    DebugMsg(sMsg);
                }
            }
        }
        break;
    case INT_OP_VMS_STATE_RES:
        {
            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_VMS_MAX_STATE; ii++)
            {
                sMsg = "";
                INT_VMS_STATE *pVms = &ARes->Unit[ii];
                sVmsNmbr = String(pVms->VMS_CTLR_NMBR);
                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    memcpy(&pObj->STATE, pVms, sizeof(INT_VMS_STATE));

                    if      (pObj->STATE.OprMode == 'A') pObj->OPER_MODE = "A";
                    else if (pObj->STATE.OprMode == 'B') pObj->OPER_MODE = "B";
                    else                                 pObj->OPER_MODE = "F";

                    //pObj->VMS_PHSE_CHNG_CYCL    = pObj->STATE.ScheduledMessageOperatingTime;
#if 0
                    pObj->VMS_CMNC_ERR_BASS_VAL = pObj->STATE.ModuleOperatingTemperature;
                    pObj->FAN_MTNS_TMPR         = pObj->STATE.FanOperatingTemperature;
                    pObj->HETR_MTNS_TMPR        = pObj->STATE.HeaterOperatingTemperature;
                    pObj->VMS_MODL_ERR_RATE     = pObj->STATE.ModuleBasicFailureRate;
#endif

                    pObj->CheckRunState();

                    if (pObj->STATE.Comm != vms_comm_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();
        }
        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;
    case INT_OP_VMS_FORM_DOWNLOAD:
        {
            char szDateTime[INT_VMS_MAX_DATETIME+1];
            char szVmsNmbr[INT_VMS_MAX_ID+1];
            INT_VMS_FORM_DOWNLOAD_REQ *AReq = (INT_VMS_FORM_DOWNLOAD_REQ*)pData;

            //sMsg.printf(L"*** VMS 폼 다운로드 메시지 수신: %d EA", AReq->Count);
            sMsg.printf(L"*** VMS Form Download Recieved: %d EA", AReq->Count);
            DebugMsg(sMsg);

            for (int ii = 0; ii < AReq->Count && ii < INT_VMS_MAX_FORM_DOWNLOAD; ii++)
            {
                sMsg = "";

                INT_VMS_FORM_DOWNLOAD *pVms = &AReq->Unit[ii];
                sprintf(szVmsNmbr, "%.*s", INT_VMS_MAX_ID, (char*)pVms->VmsId);
                sprintf(szDateTime, "%.*s", INT_VMS_MAX_DATETIME, (char*)pVms->Date);

                sVmsNmbr = String(szVmsNmbr);
                String sDateTime = String(szDateTime);

                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sVmsNmbr);
                if (pObj)
                {
                    bool bDnLd = (pVms->Result == vms_download_succ) ? true : false;
                    String sResult = bDnLd ? "Succ" : "Fail";

                    pObj->VmsMsg->OFFER_DT = sDateTime;
                    pObj->VmsMsg->OFFER_YN = bDnLd;

                    for (int kk = 0; kk < pObj->VmsMsg->Total && kk < INT_VMS_MAX_FORM; kk++)
                    {
                        pObj->VmsMsg->PHASE[kk].DNLD_YN = bDnLd ? "Y" : "N";
                    }

                    //sMsg.printf(L"*** ===> VMS Msg download: %s, %s", pObj->VMS_CTLR_ID.c_str(), sResult.c_str());
                    //DebugMsg(sMsg);
                }
                else
                {
                    sMsg.printf(L"*** INT_OP_VMS_FORM_DOWNLOAD VMS not found: %s", sVmsNmbr.c_str());
                    DebugMsg(sMsg);
                }
            }
            RefreshVmsMessage(WM_VMS_STATE_REFRESH);
            RefreshVmsMessage(WM_VMS_FORM_REFRESH);
        }
        break;
    }
    TmrCommTimeout->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::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 (NVMS0100M->Enabled)
    {
        hWnd = FindChildWindow("VMS0100M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
    if (NVMS0200M->Enabled)
    {
        hWnd = FindChildWindow("VMS0200M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
    if (NVMS0300M->Enabled)
    {
        hWnd = FindChildWindow("VMS0300M");
        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 (NVMS0500M->Enabled)
    {
        hWnd = FindChildWindow("VMS0500M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
    if (NVMS0600M->Enabled)
    {
        hWnd = FindChildWindow("VMS0600M");
        if (hWnd) POST_MSG(hWnd, AMsg, AWParam, ALParam);
    }
}
//---------------------------------------------------------------------------

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

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

#if 0
    bool bShow = false;
    try
    {
        ItsFacilityManager->FLists.Lock();
        try
        {
            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 TFrmVmsOprMain::NVMSM100MClick(TObject *Sender)
{
    FORMSHOW(VMSM100M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM200MClick(TObject *Sender)
{
    FORMSHOW(VMSM200M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM210MClick(TObject *Sender)
{
    FORMSHOW(VMSM210M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM300MClick(TObject *Sender)
{
    //FORMSHOW(VMSM300M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM310MClick(TObject *Sender)
{
    //FORMSHOW(VMSM310M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM400MClick(TObject *Sender)
{
    FORMSHOW(VMSM400M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM410MClick(TObject *Sender)
{
    FORMSHOW(VMSM410M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM420MClick(TObject *Sender)
{
    FORMSHOW(VMSM420M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM430MClick(TObject *Sender)
{
    FORMSHOW(VMSM430M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM500MClick(TObject *Sender)
{
    FORMSHOW(VMSM500M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM600MClick(TObject *Sender)
{
    FORMSHOW(VMSM600M);
}
//---------------------------------------------------------------------------


void __fastcall TFrmVmsOprMain::NVMSM700MClick(TObject *Sender)
{
    FORMSHOW(VMSM700M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM800MClick(TObject *Sender)
{
    FORMSHOW(VMSM800M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMSM900MClick(TObject *Sender)
{
    FORMSHOW(VMSM900M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMS0000MClick(TObject *Sender)
{
    FORMSHOW(VMS0000M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMS0100MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(VMS0100M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMS0010MClick(TObject *Sender)
{
    FORMSHOW(VMS0010M);
}
//---------------------------------------------------------------------------
void __fastcall TFrmVmsOprMain::NVMS0200MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(VMS0200M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMS0300MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(VMS0300M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMS0400MClick(TObject *Sender)
{
    //FORMSHOW(VMS0400M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMS0500MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(VMS0500M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NVMS0600MClick(TObject *Sender)
{
if (g_AppCfg.bOnlyOneScreen) CloseChildWindow();
    FORMSHOW(VMS0600M);
}
//---------------------------------------------------------------------------

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

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

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

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

void __fastcall TFrmVmsOprMain::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 TFrmVmsOprMain::NVMS0TESTClick(TObject *Sender)
{
//
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::NTST0000MClick(TObject *Sender)
{
#if 0
VmsCtlrManager->LoadVmsMsg();
    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

#include <stdio.h>
    AnsiString sQry1 = "INSERT INTO TB_OPERSYST_MENU VALUES('%s', 'VMS.%02d.%s', 'N', 1, '');\n";
    AnsiString sQry2 = "INSERT INTO TB_OPERSYST_MENU VALUES('%s', '%s', 'N', 2, '%s');\n";
    AnsiString sMenuFile = g_sAppDir + "Menu_VMS.TXT";
    FILE      *pFileMenu = NULL;
    pFileMenu = fopen(sMenuFile.c_str(), "w+");
    if (pFileMenu == NULL)
    {
        ShowMessage("메뉴파일을 생성하지 못하였습니다.");
        return;
    }

    int nMenuCnt = 1;
    int nMenuTabs = Ribbon->Tabs->Count;
    for (int ii = 0; ii < nMenuTabs; ii++)
    {
        TdxRibbonTab *pTab = Ribbon->Tabs->Items[ii];
        if (pTab->Visible == false) continue;

        AnsiString sMainName = pTab->Name;
        AnsiString sMainCap  = pTab->Caption;
        fprintf(pFileMenu, sQry1.c_str(), sMainName.c_str(), nMenuCnt++, sMainCap.c_str());

        int nSubMenus = pTab->Groups->Count;
        for (int jj = 0; jj < nSubMenus; jj++)
        {
            TdxRibbonTabGroup *pGroup = pTab->Groups->Items[jj];
            TdxBar *pBar = pGroup->ToolBar;
            if (pBar->Visible == false) continue;

            int nMenus = pBar->ItemLinks->Count;
            for (int kk = 0; kk < nMenus; kk++)
            {
                TdxBarItemLink *pItemLink = pBar->ItemLinks->Items[kk];
                TdxBarLargeButton *pMenuBtn = (TdxBarLargeButton*)pItemLink->Item;
                if (pMenuBtn->Visible != ivAlways) continue;

                AnsiString sMenuName = pMenuBtn->Name;
                AnsiString sMenuCap  = pMenuBtn->Caption;
                fprintf(pFileMenu, sQry2.c_str(), sMenuName.c_str(), sMenuCap.c_str(), sMainName.c_str());
            }
        }
    }

    fclose(pFileMenu);
    pFileMenu = NULL;
#if 0
                    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;
                            }
                        }
                    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::FormDblClick(TObject *Sender)
{
    NTST0000MClick((TObject*)NTST0000M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsOprMain::ApplicationEvents1ShortCut(TWMKey &Msg, bool &Handled)
{
#if 0
    bool bCTRL  = ::GetAsyncKeyState(VK_CONTROL);
    bool bSHIFT = ::GetAsyncKeyState(VK_SHIFT);

    switch(Msg.CharCode)
    {
       case VK_ESCAPE:
         // 선택 취소
         SelectAll(false);
         Handled = true;
         break;
       case 0xBB:
         if (bCTRL && bSHIFT)
         {
         }
         break;
    }
    //이렇게 하시면 될 것 같습니다. + 은, = 에 Shift 가 눌린것으로 검사를 하시면 되고, Ctrl 까지 연산을 하시면, Ctrl + "+" 를 검사하실수 있습니다.
    if (0 > GetKeyState(17) && 0 > GetKeyState(97))
        Shape1->Brush->Color = clRed;
    else Shape1->Brush->Color = clWhite;
    Handled = true;

    if (Msg.CharCode==37) Image2->Left -= 8;
    if (Msg.CharCode==38) Image2->Top  -= 8;
    if (Msg.CharCode==39) Image2->Left += 8;
    if (Msg.CharCode==40) Image2->Top  += 8;
    Handled = true;

   if(Msg.CharCode == 'W'){
      xkam=xkam+2*sin(kat*3.14/180);
      zkam=zkam+2*cos(kat*3.14/180);
      xcelu=xkam+200*sin(kat*3.14/180);
      zcelu=zkam+200*cos(kat*3.14/180);
   }
   if(Msg.CharCode == 'Z'){
      xkam=xkam-2*sin(kat*3.14/180);
      zkam=zkam-2*cos(kat*3.14/180);
      xcelu=xkam+200*sin(kat*3.14/180);
      zcelu=zkam+200*cos(kat*3.14/180);
   }
   if(Msg.CharCode == 'A'){
      kat=kat+4;
      xcelu=xkam+200*sin(kat*3.14/180);
      zcelu=zkam+200*cos(kat*3.14/180);
   }
   if(Msg.CharCode == 'D'){
      kat=kat-4;
      xcelu=xkam+200*sin(kat*3.14/180);
      zcelu=zkam+200*cos(kat*3.14/180);
   }
   if(Msg.CharCode == 'Q'){
      ykam=ykam+1;
      ycelu=ycelu+1;
   }
   if(Msg.CharCode == 'E'){
      ykam=ykam-1;
      ycelu=ycelu-1;
   }
   if(Msg.CharCode == 'R'){
      ycelu=ycelu+1;
   }
   if(Msg.CharCode == 'T'){
      ycelu=ycelu-1;
   }

#endif

    if (Msg.CharCode == VK_F2)
    {
        NVMS0010MClick((TObject*)NVMS0010M);
    }
    else
    if (Msg.CharCode == VK_F5)
    {
        DWORD dwTick = GetTickCount();

        FPollVmsMsg.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_VMS_DSPLMSG);
        DebugMsg(">>> VMS Display Message Request");//">>> VMS 표출메시지 조회 요청");

        FPollPrcsState.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_PROCESS_STTS);
        DebugMsg(">>> Process Status Request");//">>> 프로세스 상태 조회 요청");

        FPollVmsState.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_FACILITY_STTS);
        DebugMsg(">>> VMS Status Request");//">>> VMS 상태 조회 요청");
    }
}
//---------------------------------------------------------------------------

