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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "CDSNodeF.h"
#include "CDSLinkF.h"
#include "CDSIfscF.h"
#include "CDSRoadF.h"
#include "ITSLangTransF.h"
#include "ITSMapF.h"
#pragma hdrstop

#include "ITSSELAMF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalc"
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxEdit"
#pragma link "cxFilter"
#pragma link "cxGraphics"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "FRAME_IfscListF"
#pragma link "FRAME_LinkListF"
#pragma link "FRAME_NodeListF"
#pragma link "FRAME_OpenMapF"
#pragma link "FRAME_RoadListF"
#pragma resource "*.dfm"

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

__fastcall TITSSELAM::TITSSELAM(TComponent* Owner, int ALinkLevel/*=1*/)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    LoadLocalSkin();

    FTitle = Caption;//"구간 선택";

    FRefreshId = "";
    FSelPosX   = "0";
    FSelPosY   = "0";

    FSelected  = false;
    FMultiSelect = false;

    FLinkId = "";
    FPosX = FPosY = 0;

	FMouseDownPosX = FMouseDownPosY = 0;

    PgList->Properties->ActivePage = TabNode;
    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<선택구간목록>";

    FRAMENodeList1->PnlTop->Visible = false;
    FRAMENodeList1->PnlBottom->Visible = false;

    FRAMELinkList1->PnlTop->Visible = false;
    FRAMELinkList1->PnlBottom->Visible = false;

    FRAMEIfscList1->PnlTop->Visible = false;
    FRAMEIfscList1->PnlBottom->Visible = false;

    FRAMERoadList1->PnlTop->Visible = false;
    FRAMERoadList1->PnlBottom->Visible = false;

    FLinkLevel = ALinkLevel;

    ITSSELAM = this;

    FLayerIdx = LyrTp_Node;
    FRAMEOpenMap1->LayerIdx = FLayerIdx;
    FRAMEOpenMap1->ChkShowNmbr->Visible = false;
    FRAMEOpenMap1->MapCallbackFunc = TITSSELAM_MapCallback;
}
//---------------------------------------------------------------------------

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

void __fastcall TITSSELAM::LoadLocalSkin()
{
}
//---------------------------------------------------------------------------

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

    FRAMEOpenMap1->OpenMap();

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

void __fastcall TITSSELAM::SetLinkLevel(int ALinkLevel)
{
    TabLink->Visible = false;
    TabLink->TabVisible = false;
    TabServiceLink->Visible = false;
    TabServiceLink->TabVisible = false;
    TabRoad->Visible = false;
    TabRoad->TabVisible = false;

    switch(ALinkLevel)
    {
    case 1:
        FRAMELinkList1->UpdateList();
        TabLink->Visible = true;
        TabLink->TabVisible = true;
        TabServiceLink->Visible = false;
        TabServiceLink->TabVisible = false;
        TabRoad->Visible = false;
        TabRoad->TabVisible = false;
        break;
    case 2:
        FRAMEIfscList1->UpdateList();
        TabLink->Visible = false;
        TabLink->TabVisible = false;
        TabServiceLink->Visible = true;
        TabServiceLink->TabVisible = true;
        TabRoad->Visible = false;
        TabRoad->TabVisible = false;
        break;
    case 3:
        FRAMERoadList1->UpdateList();
        TabLink->Visible = false;
        TabLink->TabVisible = false;
        TabServiceLink->Visible = false;
        TabServiceLink->TabVisible = false;
        TabRoad->Visible = true;
        TabRoad->TabVisible = true;
        break;
    default: return;
    }

    FLinkLevel = ALinkLevel;
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::FormInit()
{
    if (FRAMEOpenMap1->MapStart)
    {
        int nRow;
        TcxDataController *pGDC = TvList->DataController;
        try
        {
            int nSeq = 1;
            for (int ii = 0; ii < pGDC->RecordCount; ii++)
            {
                String sLinkId = pGDC->Values[ii][Column01->Index];

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

    FRAMENodeList1->UpdateList();
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    BtnSearchClick((TObject*)BtnSearch);
    Application->ProcessMessages();

    cxGroupBox1->Caption = cxGroupBox1->Caption + "  - Level: " + String(LinkLevel);

    RefreshLink();
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::BtnSearchClick(TObject *Sender)
{
    Application->ProcessMessages();
    RefreshData();
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::RefreshData()
{
}
//---------------------------------------------------------------------------

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

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

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

    int nIndex = Sender->DataController->FocusedRecordIndex;
    if (nIndex < 0) return;

    String sNodeId = VarToStr(Sender->DataController->Values[nIndex][FRAMENodeList1->Column01->Index]);

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

void __fastcall TITSSELAM::FRAMELinkList1TvListCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
    int nIndex = Sender->DataController->FocusedRecordIndex;
    if (nIndex < 0) return;

    SelGisItem(1, Sender->DataController->Values[nIndex][FRAMELinkList1->Column01->Index]);
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::FRAMEIfscList1TvListCellClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
    int nIndex = Sender->DataController->FocusedRecordIndex;
    if (nIndex < 0) return;

    SelGisItem(2, Sender->DataController->Values[nIndex][FRAMEIfscList1->Column01->Index]);
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::FRAMERoadList1TvListCellClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
    int nIndex = Sender->DataController->FocusedRecordIndex;
    if (nIndex < 0) return;

    SelGisItem(3, Sender->DataController->Values[nIndex][FRAMERoadList1->Column01->Index]);
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::BtnSelectClick(TObject *Sender)
{
    if (TvList->DataController->RecordCount <= 0)
    {
        Application->MessageBox(lblText1->Caption.c_str(),//L"구간이 선택되지 않았습니다.\r\n지도에서 구간을 선택하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    FLinkId = EdLinkId->Text.Trim();
    FSelected = true;
    Close();
    Application->ProcessMessages();
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::SelGisItem(int AType, String AId)
{
    if (!FRAMEOpenMap1->MapStart) return;

    sJs.printf(L"extentLayerObject(%d, '%s')", LyrTp_Traffic, AId.c_str());
    FRAMEOpenMap1->ExecScript(sJs);
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::BtnDeleteClick(TObject *Sender)
{
    try
    {
        TcxDataController *pGDC = TvList->DataController;
        TvList->BeginUpdate();
        try
        {
            for (int ii = 0; ii < pGDC->RecordCount; ii++)
            {
                String sLinkId = pGDC->Values[ii][Column01->Index];
                DeleteSelect(sLinkId);
            }
            TvList->Controller->DeleteSelection();
        }
        catch(...)
        {
        }
    }
    __finally
    {
        TvList->EndUpdate();
    }
    RefreshLink();
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::UpdateSelect(String ALinkId, double X, double Y)
{
    try
    {
        int nRow;
        TcxDataController *pGDC = TvList->DataController;
        TvList->BeginUpdate();
        try
        {
            bool bAdd = true;
            if (!FMultiSelect)
            {
                for (int ii = 0; ii < pGDC->RecordCount; ii++)
                {
                    String sLinkId = pGDC->Values[ii][Column01->Index];
                    DeleteSelect(sLinkId);
                }
                CMM_ClearGridTableView(TvList);
            }
            else
            {
                for (int ii = 0; ii < pGDC->RecordCount; ii++)
                {
                    String sTmpLinkId = pGDC->Values[ii][Column01->Index];
                    if (sTmpLinkId == ALinkId)
                    {
                        pGDC->Values[ii][Column02->Index] = X;
                        pGDC->Values[ii][Column03->Index] = Y;
                        bAdd = false;
                        break;
                    }
                }
            }

            if (bAdd)
            {
                nRow = pGDC->AppendRecord();
                pGDC->Values[nRow][Column01->Index] = ALinkId;
                pGDC->Values[nRow][Column02->Index] = X;
                pGDC->Values[nRow][Column03->Index] = Y;
            }
        }
        catch(...)
        {
        }
    }
    __finally
    {
        TvList->EndUpdate();
    }

    RefreshLink();
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::DeleteSelect(String ALinkId)
{
    if (!FRAMEOpenMap1->MapStart) return;

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

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

    int nIndex = Sender->DataController->FocusedRecordIndex;
    if (nIndex < 0) return;

    String sLinkId = VarToStr(Sender->DataController->Values[nIndex][Column01->Index]);
    String sX      = VarToStr(Sender->DataController->Values[nIndex][Column02->Index]);
    String sY      = VarToStr(Sender->DataController->Values[nIndex][Column03->Index]);

    if (!FRAMEOpenMap1->MapStart) return;

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

    sJs.printf(L"selectPos(0, '%s', '%s')", sX.c_str(), sY.c_str());
    FRAMEOpenMap1->ExecScript(sJs);
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::UpdateNode()
{
    if (!FRAMEOpenMap1->MapStart) return;

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

    String arrObj = "";
    String sTemp;

    int cnt = 0;
    ItsNodeManager->FLists.Lock();
    try
    {
        FOR_STL(TItsNode*, pObj, ItsNodeManager->FLists)
        {
            if (arrObj != "") arrObj += "|";

            if (cnt == 0)
            {
                sTemp.printf(L"%s,%s,%s,%.6f,%.6f,0,0,0,0", pObj->NODE_ID.c_str(), pObj->NODE_ID.c_str(), pObj->NODE_NAME.c_str(), pObj->X_CRDN, pObj->Y_CRDN);
                arrObj += sTemp;
                sJs.printf(L"addFacility(%d, '%s')", FLayerIdx, arrObj.c_str());
                FRAMEOpenMap1->ExecScript(sJs);
            }
            else
            {
                sTemp.printf(L"%s,%s,%s,%.6f,%.6f,0,0,0,0", pObj->NODE_ID.c_str(), pObj->NODE_ID.c_str(), pObj->NODE_NAME.c_str(), pObj->X_CRDN, pObj->Y_CRDN);
                sJs.printf(L"addFacilityObject(%d, '%s')", FLayerIdx, sTemp.c_str());
                FRAMEOpenMap1->ExecScript(sJs);
            }
            cnt++;
        }
    }
    __finally
    {
        ItsNodeManager->FLists.UnLock();
#if 0
        if (arrObj != "")
        {
            sJs.printf(L"addFacility(%d, '%s')", FLayerIdx, arrObj.c_str());
            FRAMEOpenMap1->ExecScript(sJs);
        }
#endif
        sJs.printf(L"showLayer(%d, 0)", FLayerIdx);
        FRAMEOpenMap1->ExecScript(sJs);
    }
}
//---------------------------------------------------------------------------

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

    TItsVrtx* pVrtx;
    TItsNode* pNode;
    String    STRT_NM;
    String    END_NM;

    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 TITSSELAM::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("setMouseClick(1)");

            //노드아이콘 등록
            UpdateNode();

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

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

            //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];
                String sLinkX   = pStringList->Strings[2];
                String sLinkY   = pStringList->Strings[3];
                String sX       = pStringList->Strings[4];
                String sY       = pStringList->Strings[5];

                UpdateSelect(sLinkId, sX.ToDouble(), sY.ToDouble());
            }
            catch(Exception &e)
            {
            }
            delete pStringList;
        }
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TITSSELAM::RefreshLink()
{
    if (!FRAMEOpenMap1->MapStart) return;

    try
    {
        int nRow;
        TcxDataController *pGDC = TvList->DataController;
        TvList->BeginUpdate();
        try
        {
            int nSeq = 1;
            for (int ii = 0; ii < pGDC->RecordCount; ii++)
            {
                pGDC->Values[ii][ColSeq->Index] = nSeq;
                String sLinkId = pGDC->Values[ii][Column01->Index];

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

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

void __fastcall TITSSELAM::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    FRAMEOpenMap1->OnCloseQuery(CanClose);
}
//---------------------------------------------------------------------------

