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

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

#include "VMSM100MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxDropDownEdit"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxTextEdit"
#pragma link "cxTimeEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#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 "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "FRAME_OpenMapF"
#pragma link "FRAME_VmsListF"
#pragma link "cxContainer"
#pragma link "cxButtons"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxDropDownEdit"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxTextEdit"
#pragma link "cxTimeEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#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 "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "FRAME_OpenMapF"
#pragma link "FRAME_VmsListF"
#pragma link "cxButtons"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxDropDownEdit"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxTextEdit"
#pragma link "cxTimeEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#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 "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "FRAME_OpenMapF"
#pragma link "FRAME_VmsListF"
#pragma resource "*.dfm"

TVMSM100M *VMSM100M = NULL;
//---------------------------------------------------------------------------
void TVMSM100M_MapCallback(TObject *ASender, const String AFunc, const String AArgs, const bool AFirst)
{
    try
    {
        if (!VMSM100M) return;
        VMSM100M->OpenMapCallback(ASender, AFunc, AArgs, AFirst);
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

__fastcall TVMSM100M::TVMSM100M(TComponent* Owner)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FUpdate= false;
    FTitle = Caption;//"VMS 기본정보 관리";

    //FRAMEVmsList1->Column02->Visible = false;
    FRAMEVmsList1->PnlTop->Visible = false;
    FRAMEVmsList1->PnlBottom->Visible = false;
    FRAMEVmsList1->ColumnSel->Visible = false;

    FRAMEVmsList1->Column06->Visible = true;
    FRAMEVmsList1->Column07->Visible = false;
    FRAMEVmsList1->Column08->Visible = true;
    FRAMEVmsList1->Column09->Visible = true;
    FRAMEVmsList1->Column10->Visible = true;
    FRAMEVmsList1->Column13->Visible = true;

    EdCmncPort->Visible = false;

    m_pGDC = FRAMEVmsList1->TvList->DataController;

    FLayerIdx = LyrTp_Vms;
    FRAMEOpenMap1->ChkShowNmbr->Caption = "VMS 번호";
    FRAMEOpenMap1->LayerIdx = FLayerIdx;
    FRAMEOpenMap1->MapCallbackFunc = TVMSM100M_MapCallback;

    SeMaxPhase->Properties->MaxValue = INT_VMS_MAX_FORM;

    EditMode = false;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::FormShow(TObject *Sender)
{
    Refresh();

    FRAMEOpenMap1->OpenMap();

    APP_FillVmsSizeType(CbType);
    //APP_FillCode(CbUsagType, "VUT");
    //APP_FillCode(CbType,     "VMP");

    VmsCtlrManager->FLists.Lock();
    try
    {
        FOR_STL(TVmsCtlr*, pObj, VmsCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;
            pObj->FData3 = NULL;
        }
    }
    __finally
    {
        VmsCtlrManager->FLists.UnLock();
    }

    FormInit();
    ChangeEditMode(1);
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::FormInit()
{
	EdNmbr->Text = "";
    EdVmsId->Text = "";
	EdVmsNm->Text = "";
    SeMaxPhase->Value = INT_VMS_MAX_FORM;

	//CbUsagType->ItemIndex = 0;
	CbType->ItemIndex = 0;

    SePosX->Value = 0;
    SePosY->Value = 0;

    EdCtlrIp->Text = "";
    EdCmncPort->Text = "";

    EdWebCamIp->Text = "";
    EdWebCamPort->Text = "";
    EdWebCamId->Text = "";
	EdWebCamPswd->Text = "";
	EdWebCamStrm->Text = "";
    ISTL_LCTN_NM->Text = "";
    ISTL_LCTN_ADDR->Text = "";

	cxTimeOn->Clear();
	cxTimeOff->Clear();
    cxTimeOn->EditValue = Now().FormatString("hh:nn");
    cxTimeOn->EditValue = "00:00";
    cxTimeOff->EditValue = Now().FormatString("hh:nn");
    cxTimeOff->EditValue = "00:00";

    FNewDb = false;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    FRAMEVmsList1->UpdateList();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::BtnCloseClick(TObject *Sender)
{
    Close();
}
//---------------------------------------------------------------------------

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

void __fastcall TVMSM100M::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    if (FUpdate)
    {
        POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_14, 0);
    }

    FRAMEVmsList1->OnCloseQuery(CanClose);
    FRAMEOpenMap1->OnCloseQuery(CanClose);
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::DisplayInfo(TVmsCtlr* AObj, bool AMoveObj/*=true*/)
{
    FormInit();

    if (!AObj) return;

    if (AMoveObj)
    {
        sJs.printf(L"selectLayerObject(%d, '%s', %d)", FLayerIdx, AObj->VMS_CTLR_NMBR.c_str(), FRAMEOpenMap1->MapZoom);
        FRAMEOpenMap1->ExecScript(sJs);
    }
	EdNmbr->Text  = String(AObj->VMS_CTLR_NMBR);
    EdVmsId->Text = AObj->VMS_CTLR_ID;
	EdVmsNm->Text = AObj->VMS_NM;

	//APP_SetCode(CbUsagType, AObj->VMS_USAG_TYPE_CD);
	APP_SetCode(CbType,     AObj->VMS_TYPE_CD);

    SePosX->Value = AObj->X_CRDN;
    SePosY->Value = AObj->Y_CRDN;

    EdCtlrIp->Text = AObj->VMS_CTLR_IP;
    //EdCmncPort->Text = AObj->VMS_CMNC_PORT;

    EdWebCamIp->Text   = AObj->WEB_CMRA_IP;
    EdWebCamPort->Text = AObj->WEB_CMRA_PORT;
    EdWebCamId->Text   = AObj->WEB_CMRA_ID;
	EdWebCamPswd->Text = AObj->WEB_CMRA_PWD;
	EdWebCamStrm->Text = AObj->STRM_SESN_NM;
    ISTL_LCTN_NM->Text = AObj->ISTL_LCTN_NM;
    ISTL_LCTN_ADDR->Text = AObj->ISTL_LCTN_ADDR;

    SeMaxPhase->Value = AObj->VMS_MAX_PHSE_NUM;
    Se_VMS_CTLR_LOCAL_NO->Value = AObj->VMS_CTLR_LOCAL_NO;

    cxTimeOn->Clear();
    cxTimeOn->EditValue = Now().FormatString("hh:nn");
    cxTimeOn->EditValue = "00:00";
    cxTimeOff->Clear();
    cxTimeOff->EditValue = Now().FormatString("hh:nn");
    cxTimeOff->EditValue = "00:00";

    try
    {
        if (AObj->PANL_ON_TIME.Length() == 4)                        // 전팡관ON시각
        {
            String sPowerOnTime  = AObj->PANL_ON_TIME;
            sPowerOnTime.Insert(":", 3);
            cxTimeOn->EditValue = sPowerOnTime;
        }
    }
    catch(Exception &e) { }
    try
    {
        if (AObj->PANL_OFF_TIME.Length() == 4)                    // 전광판OFF시각
        {
            String sPowerOffTime = AObj->PANL_OFF_TIME;
            sPowerOffTime.Insert(":", 3);
            cxTimeOff->EditValue = sPowerOffTime;
        }
    }
    catch(Exception &e) { }

//    FRAMEGisMap1->SelectObjectByPos(SePosX->Value, SePosY->Value, true);

    ChangeEditMode(3);
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::UpdateIcon()
{
    if (!FRAMEOpenMap1->MapStart) return;

    sJs.printf(L"removeLayerObject(%d)", FLayerIdx);
    FRAMEOpenMap1->ExecScript(sJs);

    String arrObj = "";
    String sTemp;

    VmsCtlrManager->FLists.Lock();
    try
    {
        FOR_STL(TVmsCtlr*, pObj, VmsCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            if (arrObj != "") arrObj += "|";

            sTemp.printf(L"%s,%s,%s,%.6f,%.6f,0,0,0,0", pObj->VMS_CTLR_NMBR.c_str(), pObj->VMS_CTLR_ID.c_str(), pObj->VMS_NM.c_str(), pObj->X_CRDN, pObj->Y_CRDN);
            arrObj += sTemp;
        }
    }
    __finally
    {
        VmsCtlrManager->FLists.UnLock();
        if (arrObj != "")
        {
            sJs.printf(L"addFacility(%d, '%s')", FLayerIdx, arrObj.c_str());
            FRAMEOpenMap1->ExecScript(sJs);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::BtnEditClick(TObject *Sender)
{
    String sId = EdNmbr->Text;
    TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sId);

    FNewDb = false;

    if (BtnEdit->Caption == FrmLang->lblEdit->Caption)//"편집")
    {
        //편집모드 시작
        ChangeEditMode(0);
        if (pObj)
        {
            //시설물아이콘을 편집아이콘으로 변경
            //function editFacilityObject(ALyrIdx, ANmbr, AComm(0:오류-편집,1:정상), AEdit(편집모드:1-편집,0-편집취소))
            sJs.printf(L"editFacilityObject(%d, %s, 1, 1)", FLayerIdx, pObj->VMS_CTLR_NMBR.c_str());
            FRAMEOpenMap1->ExecScript(sJs);
        }
    }
    else
    {
        //편집모드 취소
        ChangeEditMode(1);
        if (pObj)
        {
            //원래 정보를 화면에 표출
            CMM_SetGridRow(FRAMEVmsList1->CxList, FRAMEVmsList1->TvList, sId, FRAMEVmsList1->Column01->Index);
            DisplayInfo(pObj, false);

#if 0
            //지도시설물아이콘을 원래아이콘으로 변경
            sJs.printf(L"editFacilityObject(%d, %s, 0, 0)", FLayerIdx, pObj->VMS_CTLR_NMBR.c_str());
            FRAMEOpenMap1->ExecScript(sJs);
#else
            //추가 모드에서 취소하는 경우 지도에 신규로 추가한 객체를 찾아서 삭제해 주는것 보다
            //새롭게 다시 그리자
            UpdateIcon();
#endif
        }
        else
        {
            //객체가 없는 경우는 추가 모드에서 취소한 경우임
            sJs.printf(L"removeFacilityObject(%d, %s)", FLayerIdx, sId.c_str());
            FRAMEOpenMap1->ExecScript(sJs);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::ChangeEditMode(int AEdit)
{
    bool bEnabled = false;
    switch(AEdit)
    {
    case 0: //편집버튼클릭
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = false;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = true;

            BtnEdit->Caption = FrmLang->lblCancel->Caption;//"취소";
            BtnEdit->Hint    = FrmLang->lblCancel->Hint;//데이터 편집 취소";
            EditMode = true;
        }
        break;
    case 1: //편집[취소]버튼클릭
        {
            FormInit(); //화면을 모두 지운다.
            BtnEdit->Enabled = false;
            BtnInsert->Enabled = true;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = false;

            BtnEdit->Caption = FrmLang->lblEdit->Caption;//"편집";
            BtnEdit->Hint    = FrmLang->lblEdit->Hint;//데이터 편집";
            //bEnabled = true;
            EditMode = false;
        }
        break;
    case 2: //추가
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = false;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = true;

            BtnEdit->Caption = FrmLang->lblCancel->Caption;//"취소";
            BtnEdit->Hint    = FrmLang->lblCancel->Hint;//데이터 편집 취소";
            EditMode = true;
        }
        break;
    case 3: //수정모드
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = true;
            BtnDelete->Enabled = true;
            BtnSave->Enabled = false;

            BtnEdit->Caption = FrmLang->lblEdit->Caption;//"편집";
            BtnEdit->Hint    = FrmLang->lblEdit->Hint;//데이터 편집";
            bEnabled = true;
            EditMode = false;
        }
        break;
    }

    if (AEdit == 0 || AEdit == 2)
    {
        FRAMEVmsList1->CxList->Enabled = false;
    }
    else
    {
        FRAMEVmsList1->CxList->Enabled = true;
    }

    PnlEdit->Enabled = EditMode;

#if 0
    EdVmsId->Enabled = bEnabled;
	EdVmsNm->Enabled = bEnabled;

	CbUsagType->Enabled = bEnabled;
	CbType->Enabled = bEnabled;

    SePosX->Enabled = bEnabled;
    SePosY->Enabled = bEnabled;

    EdCtlrIp->Enabled = bEnabled;

    EdWebCamIp->Enabled = bEnabled;
    EdWebCamPort->Enabled = bEnabled;
    EdWebCamId->Enabled = bEnabled;
	EdWebCamPswd->Enabled = bEnabled;
	EdWebCamStrm->Enabled = bEnabled;

	cxTimeOn->Enabled = bEnabled;
	cxTimeOff->Enabled = bEnabled;
#endif

#if 0
	EdRseId->Properties->ReadOnly = bEnabled;
	EdRoadSpotId->Properties->ReadOnly = bEnabled;
	EdLogCnncId->Properties->ReadOnly = bEnabled;
	EdLogCnncPwd->Properties->ReadOnly = bEnabled;
	EdIstlLctnNm->Properties->ReadOnly = bEnabled;
    SePosX->Properties->ReadOnly = bEnabled;
    SePosY->Properties->ReadOnly = bEnabled;
	EdIP->Properties->ReadOnly = bEnabled;
	EdPort->Properties->ReadOnly = bEnabled;
	CbMnfcCmpyCd->Properties->ReadOnly = bEnabled;
	SeCLCT_ABNR_BASI->Properties->ReadOnly = bEnabled;
#endif
}
//---------------------------------------------------------------------------


void __fastcall TVMSM100M::BtnInsertClick(TObject *Sender)
{
    FormInit();
    //신규아이디를 얻어와서 화면을 초기화한다.

    int nNmbr, nId;
    if (!VmsCtlrManager->GetNextVmsId(nNmbr, nId))
    {
        Application->MessageBox(lblText1->Caption.c_str(),//L"새로운 VMS 정보를 생성하지 못하였습니다.\r\n프로그램 종료후에 다시 시도해 보세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    EdNmbr->Text = String(nNmbr);
    SePosX->Value = FRAMEOpenMap1->CenterX;
    SePosY->Value = FRAMEOpenMap1->CenterY;

    //지도에 새로운 시설물 아이콘 추가하면서 편집모드로 변경
    String arrObj = "";
    arrObj.printf(L"%d,New,New,%.6f,%.6f,1", nNmbr, FRAMEOpenMap1->CenterX, FRAMEOpenMap1->CenterY);
    sJs.printf(L"addFacilityObject(%d, '%s')", FLayerIdx, arrObj.c_str());
    FRAMEOpenMap1->ExecScript(sJs);

    ChangeEditMode(2);
    FNewDb = true;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::BtnDeleteClick(TObject *Sender)
{
    if (!FRAMEOpenMap1->MapStart) return;

    int nIdx = m_pGDC->FocusedRecordIndex;
    if (nIdx < 0) return;

    String sId = EdNmbr->Text;

    if (sId.IsEmpty())
    {
        Application->MessageBox(lblText2->Caption.c_str(),//L"삭제할 VMS를 목록에서 선택하세요.\r\n목록에서 더블클릭하여 선택합니다.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    String sMsg;
    sMsg = lblText3->Caption + ": " + sId;//"VMS번호: " + sId;
    sMsg+= "\r\n" + lblText4->Caption;//"선택하신 VMS 정보를 삭제하시겠습니까?";

    if (Application->MessageBox(sMsg.c_str(), FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

	TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sId);

	if (pObj)
	{
		if (VmsCtlrManager->DeleteVms(pObj))
		{
            pObj->DEL_YN = "Y";
            FRAMEVmsList1->UpdateList();
            UpdateIcon();
		}

        FUpdate = true;

        Application->MessageBox(lblText5->Caption.c_str(),//L"VMS 정보삭제\r\nVMS 정보를 삭제 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FormInit();
        ChangeEditMode(1);

        UpdateIcon();
	}
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::BtnSaveClick(TObject *Sender)
{
	if (EdNmbr->Text.IsEmpty()         ||
        EdVmsId->Text.Trim().IsEmpty() ||
        EdVmsNm->Text.Trim().IsEmpty() ||
        SePosX->Value == 0             ||
        SePosY->Value == 0             ||
        CbType->Text.IsEmpty()         ||
        EdCtlrIp->Text.IsEmpty())
	{
        Application->MessageBox(FrmLang->lblNecessary->Caption.c_str(),//L"★항목은 필수 입력 항목입니다.\r\n모두 입력후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    String sNmbr = EdNmbr->Text;
    int    nNmbr = sNmbr.ToInt();
    String sVmsId = EdVmsId->Text.Trim();

    if (!ITSUtil_CheckIpAddress(EdCtlrIp->Text.Trim()))
    {
        Application->MessageBox(lblText6->Caption.c_str(),//L"제어기 IP가 유효하지 않습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
    }

    if (EdWebCamIp->Text.Trim() != "")
    {
        if (!ITSUtil_CheckIpAddress(EdCtlrIp->Text.Trim()))
        {
            Application->MessageBox(lblText7->Caption.c_str(),//L"웹카메라 IP가 유효하지 않습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }
    }

    VmsCtlrManager->FLists.Lock();
    FOR_STL(TVmsCtlr*, pTmpObj, VmsCtlrManager->FLists)
    {
        if (pTmpObj->DEL_YN == "Y") continue;
        if (pTmpObj->VMS_CTLR_NMBR == sNmbr) continue; //자기자신

        if (pTmpObj->VMS_CTLR_ID == sVmsId)
        {
            Application->MessageBox(lblText8->Caption.c_str(),//L"VMS ID가 이미 사용 중입니다. VMS ID를 확인하세요.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }
    }
    VmsCtlrManager->FLists.UnLock();

    TVmsCtlr *pObj;
    if (FNewDb)
        pObj = new TVmsCtlr();
    else
        pObj = VmsCtlrManager->FLists.Find(sNmbr);

    if (pObj)
    {
        pObj->VMS_CTLR_NMBR = nNmbr;
        pObj->VMS_CTLR_ID   = sVmsId;
        pObj->VMS_NM        = EdVmsNm->Text.Trim();

        pObj->VMS_CTLR_IP       = EdCtlrIp->Text;
        pObj->VMS_CTLR_PORT     = EdCmncPort->Text.ToIntDef(0);
        pObj->VMS_CTLR_LOCAL_NO = Se_VMS_CTLR_LOCAL_NO->Value;

        pObj->VMS_TYPE_CD  = APP_GetCode(CbType);
        pObj->ISTL_LCTN_NM = ISTL_LCTN_NM->Text.Trim();
        pObj->ISTL_LCTN_ADDR = ISTL_LCTN_ADDR->Text.Trim();

        pObj->X_CRDN = SePosX->Value;
        pObj->Y_CRDN = SePosY->Value;

        pObj->WEB_CMRA_IP   = EdWebCamIp->Text;
        pObj->WEB_CMRA_PORT = EdWebCamPort->Text.ToIntDef(0);
        pObj->WEB_CMRA_ID   = EdWebCamId->Text;
        pObj->WEB_CMRA_PWD  = EdWebCamPswd->Text;
        pObj->STRM_SESN_NM  = EdWebCamStrm->Text;

        pObj->VMS_MAX_PHSE_NUM = SeMaxPhase->Value;

        pObj->PANL_ON_TIME  = cxTimeOn->Time.FormatString("HHNN");
        pObj->PANL_OFF_TIME = cxTimeOff->Time.FormatString("HHNN");



        pObj->Completed    = true;
        pObj->MEM_DEL      = "N";

        bool bResult;
        if (FNewDb)
        {
            pObj->DEL_YN = "N";
            bResult = VmsCtlrManager->InsertVms(pObj);
            if (bResult)
            {
                VmsCtlrManager->FLists.Push(sNmbr, pObj);
            }
		}
        else
		{
            bResult = VmsCtlrManager->UpdateVms(pObj);
		}

        if (bResult)
        {
            Application->MessageBox(lblText9->Caption.c_str(),//L"VMS 정보저장\r\nVMS 정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

            FUpdate = true;

            FRAMEVmsList1->UpdateList();
            UpdateIcon();
            CMM_SetGridRow(FRAMEVmsList1->CxList, FRAMEVmsList1->TvList, sNmbr, FRAMEVmsList1->Column01->Index);
            DisplayInfo(pObj, true);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::FRAMEVmsList1TvListCellDblClick(TcxCustomGridTableView *Sender,
          TcxGridTableDataCellViewInfo *ACellViewInfo, TMouseButton AButton,
          TShiftState AShift, bool &AHandled)
{
	if (!ACellViewInfo) return;
	int nRow = FRAMEVmsList1->TvList->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    int nMemPtr = FRAMEVmsList1->TvList->DataController->Values[nRow][FRAMEVmsList1->Column99->Index];
    TVmsCtlr* pObj = (TVmsCtlr*)nMemPtr;
    DisplayInfo(pObj, true);
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::EdWebCamPortKeyPress(TObject *Sender, wchar_t &Key)
{
    if (Key > '9' || Key < '0')
    {
        if (Key != VK_BACK && Key != VK_TAB && Key != '-')
            Key = 0;
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::BtnSaveAllClick(TObject *Sender)
{
    String sMsg;
    sMsg = "";
    sMsg+= "\r\n" + lblText10->Caption;//제어기 설정 정보를 전체 VMS에 동일하게 적용 하시겠습니까?";

    if (Application->MessageBox(sMsg.c_str(), FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

    TVmsCtlr* pObj = NULL;
    try
    {
        pObj = new TVmsCtlr();
        pObj->PANL_ON_TIME   = cxTimeOn->Time.FormatString("HHNN");
        pObj->PANL_OFF_TIME  = cxTimeOff->Time.FormatString("HHNN");

        if (VmsCtlrManager->UpdateCtlrInfo(pObj))
        {
            FUpdate = true;

            VmsCtlrManager->FLists.Lock();
            FOR_STL(TVmsCtlr*, pTmpObj, VmsCtlrManager->FLists)
            {
                if (pTmpObj->DEL_YN == "Y") continue;

                pTmpObj->PANL_ON_TIME   = pObj->PANL_ON_TIME;
                pTmpObj->PANL_OFF_TIME  = pObj->PANL_OFF_TIME;
            }
            VmsCtlrManager->FLists.UnLock();

            Application->MessageBox(lblText11->Caption.c_str(),//L"VMS 제어기설정 정보저장\r\n제어기 설정 정보를 전체 제어기에 적용 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
    }
    __finally
    {
        if (pObj)
        {
            delete pObj;
            pObj = NULL;
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM100M::SeMaxPhasePropertiesChange(TObject *Sender)
{
    if (((TcxSpinEdit*)Sender)->Value < ((TcxSpinEdit*)Sender)->Properties->MinValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MinValue;
    else if(((TcxSpinEdit*)Sender)->Value > ((TcxSpinEdit*)Sender)->Properties->MaxValue &&
        ((TcxSpinEdit*)Sender)->Properties->MaxValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MaxValue;
}
//---------------------------------------------------------------------------
void __fastcall TVMSM100M::OpenMapCallback(TObject *ASender, const String AFunc, const String AArgs, const bool AFirst)
{
    try
    {
        if (AFirst)
        {
            //지도를 편집모드로 변경
            sJs.printf(L"setEditMode(%d, 1)", FLayerIdx);
            FRAMEOpenMap1->ExecScript(sJs);
            //시설물아이콘 등록
            UpdateIcon();
            sJs.printf(L"extentLayer(%d)", FLayerIdx);
            FRAMEOpenMap1->ExecScript(sJs);
            return;
        }

        if (AFunc.Pos("onfacilitydragend"))
        {
            TStringList *pStringList = new TStringList;
            pStringList->CommaText = AArgs;

            try
            {
                String sNmbr      = pStringList->Strings[0];
                String sCenterLat = pStringList->Strings[1];
                String sCenterLng = pStringList->Strings[2];
                SePosX->Value = sCenterLat.ToDouble();
                SePosY->Value = sCenterLng.ToDouble();
            }
            catch(Exception &e)
            {
            }
            delete pStringList;
        }
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------
#if 0
String __fastcall TVMSM100M::GetPassword(String APswd)
{
    int    nRes;
    String sEncPswd = "";
    String sQry;

#if 0
select scp.enc_b64('DAMO','SCP','ARIA_256.SCPS','admin13579') from dual;
select scp.dec_b64('DAMO','SCP','ARIA_256.SCPS','+58lKndUaKrNQxoLEKc4Ew==') from dual;
#endif

#if 1
#if 0
    sQry = "SELECT SCP.HASH_B64('71', :p01) AS PWD FROM DUAL \r\n";
#else
    sQry = "SELECT :p01 AS PWD FROM DUAL \r\n";
#endif

    TADOQuery *pADO = NULL;
    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
            pADO->Connection = ITSDb_GetConnection();
            pADO->Close();
            pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = APswd;
            pADO->Prepared = true;
            pADO->Open();
            if (!pADO->Eof)
            {
                pADO->First();
                sEncPswd = pADO->FieldByName("PWD")->AsString;
            }
            pADO->Close();
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName())+E.Message);
        }
        catch (Exception &exception)
        {
            throw Exception(String(exception.ClassName())+exception.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
#else
    sEncPswd = String(ITSSHA256_Encrpyt(AnsiString(APswd)));
#endif

    return sEncPswd;
}
//---------------------------------------------------------------------------
#endif

