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

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

#include "DSRM030MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalendar"
#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 "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#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 "dxSkinscxPCPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "FRAME_DsrcListF"
#pragma link "cxRadioGroup"
#pragma link "cxClasses"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDBData"
#pragma link "cxFilter"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridDBTableView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxStyles"
#pragma link "cxCheckBox"
#pragma link "cxCalc"
#pragma link "FRAME_DsrcSectListF"
#pragma link "FRAME_OpenMapF"
#pragma resource "*.dfm"

TDSRM030M *DSRM030M = NULL;
//---------------------------------------------------------------------------

void TDSRM030M_MapCallback(TObject *ASender, const String AFunc, const String AArgs, const bool AFirst)
{
    try
    {
        if (!DSRM030M) return;
        DSRM030M->OpenMapCallback(ASender, AFunc, AArgs, AFirst);
    }
    catch(Exception &exception)
    {
    }
}

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

    FUpdate= false;
    FTitle = Caption;

    TvLink->OptionsView->NoDataToDisplayInfoText = "<수집링크 정보가 없습니다>";

    FRAMEDsrcSectList1->PnlBottom->Visible = false;
    FRAMEDsrcSectList1->PnlTop->Visible = false;
    FRAMEDsrcSectList1->ColumnSel->Visible = false;
    FRAMEDsrcSectList1->Column02->Visible = false;

    m_pGDC = FRAMEDsrcSectList1->TvList->DataController;

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

    MyItsDsrcSectManager = new TItsDsrcSectManager();
    MyItsDsrcSectManager->LoadFromDb();

    FLayerIdx = LyrTp_Dsrc;
    FRAMEOpenMap1->LayerIdx = FLayerIdx;
    FRAMEOpenMap1->ChkShowNmbr->Visible = false;
    FRAMEOpenMap1->BtnMapSelect->Visible = false;
    FRAMEOpenMap1->MapCallbackFunc = TDSRM030M_MapCallback;

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

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

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

    FRAMEOpenMap1->OpenMap();

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

void __fastcall TDSRM030M::FormInit()
{
    //제공구간목록이 초기화되기전에 이전정보를 지도에서 지워준다.
    if (FRAMEOpenMap1->MapStart)
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        try
        {
            for (int ii = 0; ii < pGDC->RecordCount; ii++)
            {
                String sLinkId = pGDC->Values[ii][ColLink2->Index];

                sJs.printf(L"updateEditLink('%s', 0)", sLinkId.c_str());
                FRAMEOpenMap1->ExecScript(sJs);
            }
        }
        catch(...)
        {
        }
    }

    EdLinkId->Text = "";
    EdRseSectId->Text   = "";
    EdRseSectName->Text = "";

    EdStartSpotId->Text   = "";
    EdStartSpotNm->Text   = "";
    EdEndSpotId->Text     = "";
    EdEndSpotNm->Text     = "";
    EdRseSectLength->Text = "0";

    CMM_ClearGridTableView(TvLink);

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

void __fastcall TDSRM030M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;

    //UpdateList();
    FRAMEDsrcList1->UpdateList();
    FRAMEDsrcSectList1->UpdateList();
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::UpdateList()
{
    FRAMEDsrcSectList1->LoadFromDb();
    FRAMEDsrcSectList1->UpdateList();
}
//---------------------------------------------------------------------------

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

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

void __fastcall TDSRM030M::FormCloseQuery(TObject *Sender, bool &CanClose)
{
#if 0
    if (FUpdate)
    {
        POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_14, 0);
    }
#endif
    if (MyItsDsrcSectManager)
    {
        delete MyItsDsrcSectManager;
        MyItsDsrcSectManager = NULL;
    }
    FRAMEDsrcList1->OnCloseQuery(CanClose);
    FRAMEOpenMap1->OnCloseQuery(CanClose);
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::DisplayInfo(TItsDsrcSect* AObj)
{
    FormInit();

    if (!AObj) return;

    EdRseSectId->Text   = AObj->RSE_SECT_ID;
    EdRseSectName->Text = AObj->RSE_SECT_NM;

    EdStartSpotId->Text   = AObj->STRT_ID;
    EdStartSpotNm->Text   = AObj->STRT_SPOT_NM;
    EdEndSpotId->Text     = AObj->END_ID;
    EdEndSpotNm->Text     = AObj->END_SPOT_NM;
    EdRseSectLength->Text = AObj->DSTC;

    ChangeEditMode(3);

    DisplaySectLink(AObj);
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::DisplaySectLink(TItsDsrcSect* AObj)
{
    if (!AObj) return;

    CMM_ClearGridTableView(TvLink);

    String sLinkIds = "";
    try
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        TvLink->BeginUpdate();

        FOR_STL(TItsDsrcSectLink *, pObj, AObj->FLinkLists)
        {
            if (pObj->DEL_YN == "Y" || pObj->MEM_DEL == "Y") continue;

            String sLinkId = pObj->LINK_ID;
            nRow = pGDC->AppendRecord();
            pGDC->Values[nRow][ColLink2->Index] = sLinkId;

            TItsLink *pLink = ItsLinkManager->FLists.Find(sLinkId);
            if (pLink)
            {
                TItsNode *pNode;
                pGDC->Values[nRow][ColLink3->Index] = pLink->F_NODE_ID;
                pGDC->Values[nRow][ColLink5->Index] = pLink->T_NODE_ID;
                pNode = ItsNodeManager->FLists.Find(pLink->F_NODE_ID);
                if (pNode)
                {
                    pGDC->Values[nRow][ColLink4->Index] = pNode->NODE_NAME;
                }
                pNode = ItsNodeManager->FLists.Find(pLink->T_NODE_ID);
                if (pNode)
                {
                    pGDC->Values[nRow][ColLink6->Index] = pNode->NODE_NAME;
                }

                pGDC->Values[nRow][ColLink7->Index] = StrToInt(pLink->LINK_LENG);

                if (sLinkIds == "") sLinkIds = sLinkId;
                else                sLinkIds = sLinkIds + ","+sLinkId;
            }
            else
            {
                pGDC->Values[nRow][ColLink7->Index] = 0;
            }
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }

    RefreshSectLink();

    if (sLinkIds != "")
    {
        sJs.printf(L"extentLayerObject(%d, '%s')", LyrTp_Traffic, sLinkIds.c_str());
        FRAMEOpenMap1->ExecScript(sJs);
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::BtnEditClick(TObject *Sender)
{
    if (BtnEdit->Caption == FrmLang->lblEdit->Caption)//"편집")
    {
        ChangeEditMode(0);
        FNewDb = false;
    }
    else
    {
        String sSectId = EdRseSectId->Text;
        ChangeEditMode(1);

        CMM_SetGridRow(FRAMEDsrcSectList1->CxList, FRAMEDsrcSectList1->TvList, sSectId, FRAMEDsrcSectList1->Column01->Index);
        int nRow = FRAMEDsrcSectList1->TvList->DataController->FocusedRecordIndex;
        if( nRow <= -1 )
            return;

        int nMemPtr = FRAMEDsrcSectList1->TvList->DataController->Values[nRow][FRAMEDsrcSectList1->Column99->Index];
        TItsDsrcSect* pObj = (TItsDsrcSect*)nMemPtr;
        DisplayInfo(pObj);

#if 0
        TItsDsrcSect *pObj = MyItsDsrcSectManager->FLists.Find(sSectId);
        if (pObj)
        {
            CMM_SetGridRow(FRAMEDsrcSectList1->CxList, FRAMEDsrcSectList1->TvList, sSectId, FRAMEDsrcSectList1->Column01->Index);
            DisplayInfo(pObj);
        }
#endif
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::ChangeEditMode(int AEdit)
{
    bool bGisEdit = true;
    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;
            bGisEdit = false;
            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)
    {
        FRAMEDsrcSectList1->CxList->Enabled = false;
    }
    else
    {
        FRAMEDsrcSectList1->CxList->Enabled = true;
    }

    GrpInfo->Enabled = EditMode;
    GrpLink->Enabled = EditMode;

	EdRseSectName->Properties->ReadOnly = bEnabled;

    cxCheckBox1->Enabled = !bEnabled;
    cxCheckBox2->Enabled = !bEnabled;
    BtnLinkAdd->Enabled = !bEnabled;
    BtnLinkDel->Enabled = !bEnabled;
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::BtnInsertClick(TObject *Sender)
{
    FormInit();

    //신규아이디를 얻어와서 화면을 초기화한다.
    String sSectId;
    if (!MyItsDsrcSectManager->GetNextSectId(sSectId))
    {
        Application->MessageBox(L"새로운 수집구간 ID를 생성하지 못하였습니다.\r\n프로그램 종료후에 다시 시도해 보세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    EdRseSectId->Text = sSectId;
    ChangeEditMode(2);
    FNewDb = true;
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::BtnDeleteClick(TObject *Sender)
{
    m_pGDC = FRAMEDsrcSectList1->TvList->DataController;

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

    String sSectId = EdRseSectId->Text;

    if (sSectId.IsEmpty())
    {
        Application->MessageBox(L"삭제할 DSRC 수집구간을 목록에서 선택하세요.\r\n목록에서 더블클릭하여 선택합니다.", FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    String sMsg;
    sMsg = "수집구간 ID: " + sSectId;
    sMsg+= "\r\n선택하신 DSRC 수집구간 정보를 삭제하시겠습니까?\r\n관련정보도 함께 삭제 됩니다.";

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

	TItsDsrcSect *pObj = MyItsDsrcSectManager->FLists.Find(sSectId);

	if (pObj)
	{
		if (MyItsDsrcSectManager->DeleteSect(pObj->RSE_SECT_ID))
		{
            pObj->DEL_YN = "Y";
            UpdateList();
		}

        UpdateList();

        FUpdate = true;

        Application->MessageBox(L"DSRC 수집구간 정보삭제\r\nDSRC 수집구간 정보를 삭제 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FormInit();
        ChangeEditMode(1);
	}
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::BtnSaveClick(TObject *Sender)
{
    if (EdRseSectId->Text.IsEmpty()          ||
        EdRseSectName->Text.Trim().IsEmpty() ||
        EdStartSpotNm->Text.Trim().IsEmpty() ||
        EdEndSpotNm->Text.Trim().IsEmpty()   ||
        EdStartSpotId->Text.IsEmpty()        ||
        EdRseSectLength->Text.Trim().IsEmpty()      ||
        EdEndSpotId->Text.IsEmpty()           )
	{
        Application->MessageBox(L"★항목은 필수 입력 항목입니다.\r\n모두 입력후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    String sSectId = EdRseSectId->Text;
    String STRT_ID = EdStartSpotId->Text.Trim();
    String END_ID  = EdEndSpotId->Text.Trim();

    if (TvLink->DataController->RecordCount == 0)
    {
        Application->MessageBox(L"수집구간 링크정보가 없습니다.\r\n링크정보를 입력후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
    }
    if (STRT_ID == END_ID)
    {
        Application->MessageBox(L"시점 DSRC과 종점 DSRC의 정보가 같습니다.\r\n시/종점 DSRC 정보를 확인 후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
    }


    MyItsDsrcSectManager->FLists.Lock();
    FOR_STL(TItsDsrcSect*, tmp, MyItsDsrcSectManager->FLists)
    {
        if (tmp->RSE_SECT_ID == sSectId) continue;

        if (tmp->STRT_ID == STRT_ID && tmp->END_ID == END_ID)
        {
            Application->MessageBox(L"시점 DSRC과 종점 DSRC의 정보가 이미 존재합니다.\r\n시/종점 DSRC 정보를 확인 후 진행해 주세요.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            MyItsDsrcSectManager->FLists.UnLock();
            return;
        }
    }
    MyItsDsrcSectManager->FLists.UnLock();

    TItsDsrcSect *pObj;
    if (FNewDb)
        pObj = new TItsDsrcSect();
    else
        pObj = MyItsDsrcSectManager->FLists.Find(sSectId);

    if (pObj)
    {
        pObj->RSE_SECT_ID   = sSectId;
        pObj->DSTC          = EdRseSectLength->Text.Trim();
        pObj->RSE_SECT_NM   = EdRseSectName->Text.Trim();

        pObj->STRT_ID       = STRT_ID;
        pObj->STRT_SPOT_NM  = EdStartSpotNm->Text;
        pObj->END_ID        = END_ID;
        pObj->END_SPOT_NM   = EdEndSpotNm->Text;

        pObj->DEL_YN              = "N";

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

        pObj->FLinkLists.RemoveAll();

        int nLength = 0;
        int nTmp;
        try {
            TvLink->BeginUpdate();
            for (int ii = 0; ii < TvLink->DataController->RecordCount; ii++)
            {
                String sLinkId = TvLink->DataController->Values[ii][ColLink2->Index];
                if (VarIsNull(TvLink->DataController->Values[ii][ColLink7->Index]))
                    nTmp = 0;
                else
                    nTmp = TvLink->DataController->Values[ii][ColLink7->Index];
                nLength += nTmp;

				TItsDsrcSectLink *pLinkObj = new TItsDsrcSectLink();

				pLinkObj->RSE_SECT_ID = pObj->RSE_SECT_ID;
				pLinkObj->LINK_ID     = sLinkId;
				pLinkObj->LINK_ORD    = String(ii+1);
				pLinkObj->DEL_YN      = "N";

				pObj->FLinkLists.Push(pLinkObj->LINK_ORD, pLinkObj);
            }
        }
        __finally
        {
            TvLink->EndUpdate();
            pObj->DSTC = String(nLength);
        }
        bool bResult;
        bResult = MyItsDsrcSectManager->SaveSect(pObj);

        if (bResult)
        {
            Application->MessageBox(L"DSRC 수집구간 정보저장\r\nDSRC 수집구간 정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

            if (FNewDb)
            {
                MyItsDsrcSectManager->FLists.Push(pObj->RSE_SECT_ID, pObj);
            }

            FUpdate = true;

            UpdateList();

            CMM_SetGridRow(FRAMEDsrcSectList1->CxList, FRAMEDsrcSectList1->TvList, sSectId, FRAMEDsrcSectList1->Column01->Index);
            int nRow = FRAMEDsrcSectList1->TvList->DataController->FocusedRecordIndex;
            if( nRow <= -1 )
                return;

            int nMemPtr = FRAMEDsrcSectList1->TvList->DataController->Values[nRow][FRAMEDsrcSectList1->Column99->Index];
            TItsDsrcSect* pObj = (TItsDsrcSect*)nMemPtr;
            DisplayInfo(pObj);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::RefreshSectLink()
{
    if (!FRAMEOpenMap1->MapStart) return;

    int nLength = 0;
    int nTmp;
    try
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        TvLink->BeginUpdate();
        try
        {
            int nSeq = 1;
            for (int ii = 0; ii < pGDC->RecordCount; ii++)
            {
                pGDC->Values[ii][ColSeq->Index] = nSeq;
                String sLinkId = pGDC->Values[ii][ColLink2->Index];
                if (VarIsNull(pGDC->Values[ii][ColLink7->Index]))
                    nTmp = 0;
                else
                    nTmp = pGDC->Values[ii][ColLink7->Index];
                nLength += nTmp;

                sJs.printf(L"updateEditLink('%s', %d)", sLinkId.c_str(), nSeq);
                FRAMEOpenMap1->ExecScript(sJs);
                if (nSeq++ > ITSMAP_MAX_DISPCOLOR) nSeq = 1;
            }
        }
        catch(...)
        {
        }
    }
    __finally
    {
        TvLink->EndUpdate();
        EdRseSectLength->Text = String(nLength);
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::UpdateRseIcon()
{
    if (!FRAMEOpenMap1->MapStart) return;

    String arrObj = "";
    String sTemp;
    try
    {
        try
        {
            FRAMEDsrcList1->MyItsDsrcManager->FLists.Lock();
            FOR_STL(TItsDsrc*, pObj, FRAMEDsrcList1->MyItsDsrcManager->FLists)
            {
                if (pObj->DEL_YN == "Y") continue;

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

                sTemp.printf(L"%s,%s,%s,%.6f,%.6f,0,0,0,0", pObj->DSRC_CTLR_NMBR.c_str(), pObj->DSRC_CTLR_ID.c_str(), pObj->ISTL_LCTN_NM.c_str(), pObj->X_CRDN, pObj->Y_CRDN);
                arrObj += sTemp;
            }
        }
        __finally
        {
            FRAMEDsrcList1->MyItsDsrcManager->FLists.UnLock();
            if (arrObj != "")
            {
                sJs.printf(L"addFacility(%d, '%s')", FLayerIdx, arrObj.c_str());
                FRAMEOpenMap1->ExecScript(sJs);

                sJs.printf(L"showLayerText(%d, %d)", FLayerIdx, (ChkViewIcon->Checked) ? 1: 0);
                FRAMEOpenMap1->ExecScript(sJs);
            }
        }
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::UpdateEditLink()
{
    if (!FRAMEOpenMap1->MapStart) return;

    TItsNode* pNode;
    String    STRT_NM;
    String    END_NM;
int FLinkLevel = 1;
    try
    {
        if (FLinkLevel == 1)
        {
            ItsLinkManager->FLists.Lock();
            try
            {
                FOR_STL(TItsLink*, pLink, ItsLinkManager->FLists)
                {
                    if (pLink->DEL_YN == "Y")   continue;

                    if (pLink->IsVertex)
                    {
                        pNode = ItsNodeManager->FLists.Find(pLink->F_NODE_ID);
                        if (pNode) STRT_NM = pNode->NODE_NAME; else STRT_NM = " ";
                        pNode = ItsNodeManager->FLists.Find(pLink->T_NODE_ID);
                        if (pNode) END_NM = pNode->NODE_NAME; else END_NM = " ";

                        sJs.printf(L"addEditLink('%s', '%s', '%s', '%s', '%s', '%s')",
                            pLink->LINK_ID.c_str(),
                            pLink->ROAD_NAME.c_str(),
                            STRT_NM.c_str(),
                            END_NM.c_str(),
                            pLink->X_CRDN_ARR.c_str(),
                            pLink->Y_CRDN_ARR.c_str());

                        FRAMEOpenMap1->ExecScript(sJs);
                    }
                }
            }
            __finally
            {
                ItsLinkManager->FLists.UnLock();
            }
            FRAMEOpenMap1->ExecScript("makeEditLinkLayer()");
        }
        else
        if (FLinkLevel == 2)
        {
            ItsIfscManager->FLists.Lock();
            try
            {
                FOR_STL(TItsIfsc*, pIfsc, ItsIfscManager->FLists)
                {
                    if (pIfsc->DEL_YN == "Y")   continue;

                    if (pIfsc->IsVertex)
                    {
                        sJs.printf(L"addEditLink('%s', '%s', '%s', '%s', '%s', '%s')",
                            pIfsc->IFSC_ID.c_str(),
                            pIfsc->IFSC_NM.c_str(),
                            pIfsc->STRT_NM.c_str(),
                            pIfsc->END_NM.c_str(),
                            pIfsc->X_CRDN_ARR.c_str(),
                            pIfsc->Y_CRDN_ARR.c_str());

                        FRAMEOpenMap1->ExecScript(sJs);
                    }
                }
            }
            __finally
            {
                ItsIfscManager->FLists.UnLock();
            }
            FRAMEOpenMap1->ExecScript("makeEditLinkLayer()");
        }
        else
        if (FLinkLevel == 3)
        {
            ItsRoadManager->FLists.Lock();
            try
            {
                FOR_STL(TItsRoad*, pRoad, ItsRoadManager->FLists)
                {
                    if (pRoad->DEL_YN == "Y")   continue;

                    if (pRoad->IsVertex)
                    {
                        sJs.printf(L"addEditLink('%s', '%s', '%s', '%s', '%s', '%s')",
                            pRoad->ROAD_ID.c_str(),
                            pRoad->ROAD_NM.c_str(),
                            pRoad->STRT_NM.c_str(),
                            pRoad->END_NM.c_str(),
                            pRoad->X_CRDN_ARR.c_str(),
                            pRoad->Y_CRDN_ARR.c_str());

                        FRAMEOpenMap1->ExecScript(sJs);
                    }
                }
            }
            __finally
            {
                ItsRoadManager->FLists.UnLock();
            }
            FRAMEOpenMap1->ExecScript("makeEditLinkLayer()");
        }
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::TvLinkCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
    if (!FRAMEOpenMap1->MapStart) return;

	if (!ACellViewInfo) return;
	int nRow = TvLink->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    String sLinkId = TvLink->DataController->Values[nRow][ColLink2->Index];
    sJs.printf(L"extentLayerObject(%d, '%s')", LyrTp_Traffic, sLinkId.c_str());
    FRAMEOpenMap1->ExecScript(sJs);
    //EdLinkId->Text = sLinkId;
}
//---------------------------------------------------------------------------

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

    int nMemPtr = FRAMEDsrcList1->TvList->DataController->Values[nRow][FRAMEDsrcList1->Column99->Index];
    TItsDsrc* pObj = (TItsDsrc*)nMemPtr;

    sJs.printf(L"selectLayerObject(%d, '%s', %d)", FLayerIdx, pObj->DSRC_CTLR_NMBR.c_str(), FRAMEOpenMap1->MapZoom);
    FRAMEOpenMap1->ExecScript(sJs);
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::cxCheckBox1Click(TObject *Sender)
{
    if (cxCheckBox1->Checked)
    {
        if (cxCheckBox2->Checked) cxCheckBox2->Checked = false;
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::cxCheckBox2Click(TObject *Sender)
{
    if (cxCheckBox2->Checked)
    {
        if (cxCheckBox1->Checked) cxCheckBox1->Checked = false;
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::BtnLinkDelClick(TObject *Sender)
{
    int nSelRows = TvLink->Controller->SelectedRowCount;
    if (nSelRows <= 0)
    {
        Application->MessageBox(L"삭제를 원하는 링크구간을 목록에서 선택하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    for (int ii = 0; ii < nSelRows; ii++)
    {
        int nSelIdx = TvLink->Controller->SelectedRows[ii]->RecordIndex;

        String sLinkId = TvLink->DataController->Values[nSelIdx][ColLink2->Index];
        sJs.printf(L"updateEditLink('%s', 0)", sLinkId.c_str());
        FRAMEOpenMap1->ExecScript(sJs);
    }
    TvLink->Controller->DeleteSelection();
    //RefreshSectLink();
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::BtnLinkAddClick(TObject *Sender)
{
    if (EdLinkId->Text.IsEmpty()) return;

    String sNewId = EdLinkId->Text;
    bool bFound = false;
    try
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        TvLink->BeginUpdate();

        for (int ii = 0; ii < pGDC->RecordCount; ii++)
        {
            String sLinkId = pGDC->Values[ii][ColLink2->Index];
            if (sNewId == sLinkId)
            {
                bFound = true;
                break;
            }
        }
        if (bFound)
        {
            Application->MessageBox(L"이미 등록되어 있는 링크구간 입니다.\r\n링크구간은 중복해서 등록 할 수 없습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }

        TItsLink *pLink = ItsLinkManager->FLists.Find(sNewId);
        if (pLink)
        {
            nRow = pGDC->AppendRecord();
            pGDC->Values[nRow][ColLink2->Index] = sNewId;

            TItsNode *pNode;
            pGDC->Values[nRow][ColLink3->Index] = pLink->F_NODE_ID;
            pGDC->Values[nRow][ColLink5->Index] = pLink->T_NODE_ID;
            pNode = ItsNodeManager->FLists.Find(pLink->F_NODE_ID);
            if (pNode)
            {
                pGDC->Values[nRow][ColLink4->Index] = pNode->NODE_NAME;
            }
            pNode = ItsNodeManager->FLists.Find(pLink->T_NODE_ID);
            if (pNode)
            {
                pGDC->Values[nRow][ColLink6->Index] = pNode->NODE_NAME;
            }

            pGDC->Values[nRow][ColLink7->Index] = StrToInt(pLink->LINK_LENG);
        }
        else
        {
            Application->MessageBox(L"데이터베이스에 등록되어 있지 않는 링크구간 입니다.\r\n데이터베이스의 정보를 확인하세요.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }
    EdLinkId->Text = "";

    RefreshSectLink();
}
//---------------------------------------------------------------------------

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

    int nMemPtr = FRAMEDsrcSectList1->TvList->DataController->Values[nRow][FRAMEDsrcSectList1->Column99->Index];
    TItsDsrcSect* pObj = (TItsDsrcSect*)nMemPtr;
    DisplayInfo(pObj);
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::ChkGisZoomClick(TObject *Sender)
{
    GrpInfo->Visible = !ChkGisZoom->Checked;
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::AddRemoveLink(String ALinkId)
{
    TItsLink* pObj = ItsLinkManager->FLists.Find(ALinkId);
    if (!pObj) return;

    try
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        TvLink->BeginUpdate();

        for (int ii = 0; ii < pGDC->RecordCount; ii++)
        {
            String sLinkId = pGDC->Values[ii][ColLink2->Index];
            if (ALinkId == sLinkId)
            {
                //pGDC->DeleteRecord(ii);
                return;
            }
        }

        nRow = pGDC->AppendRecord();

        TItsNode *pNode;
        String sFNodeName = pObj->F_NODE_ID;
        pNode = ItsNodeManager->FLists.Find(pObj->F_NODE_ID);
        if (pNode) sFNodeName = pNode->NODE_NAME;

        String sTNodeName = pObj->T_NODE_ID;
        pNode = ItsNodeManager->FLists.Find(pObj->T_NODE_ID);
        if (pNode) sTNodeName = pNode->NODE_NAME;

        pGDC->Values[nRow][ColLink2->Index] = ALinkId;
        pGDC->Values[nRow][ColLink3->Index] = pObj->F_NODE_ID;
        pGDC->Values[nRow][ColLink5->Index] = pObj->T_NODE_ID;
        pGDC->Values[nRow][ColLink4->Index] = sFNodeName;
        pGDC->Values[nRow][ColLink6->Index] = sTNodeName;
        pGDC->Values[nRow][ColLink7->Index] = StrToInt(pObj->LINK_LENG);
    }
    __finally
    {
        TvLink->EndUpdate();
        RefreshSectLink();
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::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);

            //편집레이어 생성
            FRAMEOpenMap1->ExecScript("initEditLayer()");

            //배경링크레이어 생성
            UpdateEditLink();

            //시설물아이콘 등록
            UpdateRseIcon();

            //화면을 시설물 여역으로 확대
            sJs.printf(L"extentLayer(%d)", FLayerIdx);
            FRAMEOpenMap1->ExecScript(sJs);

            return;
        }

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

            try
            {
                String sLyrType = pStringList->Strings[0];
                String sLinkId  = pStringList->Strings[1];
                if (EditMode)
                {
                    //AddRemoveLink(sLinkId);
                    EdLinkId->Text = sLinkId;
                }
            }
            catch(Exception &e)
            {
            }
            delete pStringList;
        }
        if (AFunc.Pos("onfacilityclick"))
        {
            if (EditMode)
            {
                TStringList *pStringList = new TStringList;
                pStringList->CommaText = AArgs;

                try
                {
                    String sZoom = pStringList->Strings[0];
                    String sNmbr = pStringList->Strings[1];

                    TItsDsrc *pObj = ItsDsrcManager->FLists.Find(sNmbr);
                    if (pObj)
                    {
                        if (cxCheckBox1->Checked)
                        {
                            EdStartSpotId->Text = pObj->DSRC_CTLR_NMBR;
                            EdStartSpotNm->Text = pObj->ISTL_LCTN_NM;
                        }
                        else
                        if (cxCheckBox2->Checked)
                        {
                            EdEndSpotId->Text = pObj->DSRC_CTLR_NMBR;
                            EdEndSpotNm->Text = pObj->ISTL_LCTN_NM;
                        }
                    }
                }
                catch(Exception &e)
                {
                }
                delete pStringList;
            }
        }
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::ChkViewIconClick(TObject *Sender)
{
    if (!FRAMEOpenMap1->MapStart) return;
    sJs.printf(L"showLayerText(%d, %d)", FLayerIdx, (ChkViewIcon->Checked) ? 1: 0);
    FRAMEOpenMap1->ExecScript(sJs);
}
//---------------------------------------------------------------------------

void __fastcall TDSRM030M::ColSeqCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
	if (AViewInfo->GridRecord->RecordIndex < 0)
		return;
	if (VarIsNull(AViewInfo->Value))
		return;

	try
	{
		int nIdx = AViewInfo->Value;
		if (nIdx < 0)
			return;

		ACanvas->Brush->Color = ITSMap_GetDisplayColor(nIdx);
		ACanvas->Font->Color  = ACanvas->Brush->Color;
	}
	catch(...)
	{
	}
}
//---------------------------------------------------------------------------

