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

#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 "DSRM010MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "FRAME_DsrcListF"
#pragma link "cxButtons"
#pragma link "cxCheckBox"
#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 "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinMcSkin"
#pragma link "FRAME_OpenMapF"
#pragma resource "*.dfm"

TDSRM010M *DSRM010M = NULL;
//---------------------------------------------------------------------------

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

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

    FUpdate= false;
    FTitle = Caption;

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

    m_pGDC = FRAMEDsrcList1->TvList->DataController;

    FLayerIdx = LyrTp_Dsrc;
    FRAMEOpenMap1->LayerIdx = FLayerIdx;
    FRAMEOpenMap1->MapCallbackFunc = TDSRM010M_MapCallback;

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

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

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

    FRAMEOpenMap1->OpenMap();

    APP_FillCode(CbMnfcCmpyCd, "RMF");
#if 0
    CbMnfcCmpyCd->Properties->Items->Clear();
    TItsCode *FCodeRMF  = ItsCodeManager->FLists.Find("RMF");
    if (FCodeRMF)
    {
		FOR_STL(TItsSubCode *, pSubCode, FCodeRMF->FSubLists)
		{
			if (pSubCode->USE_YN == "N") continue;
			CbMnfcCmpyCd->Properties->Items->Add(" [" + pSubCode->CMMN_CD + "] " + pSubCode->CMMN_CD_KOR_NM);
		}
    }
	CbMnfcCmpyCd->ItemIndex = 0;
#endif

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

void __fastcall TDSRM010M::FormInit()
{
	EdId->Text = "";
	EdRseId->Text = "";
	EdRoadSpotId->Text = "";
	EdLogCnncId->Text = "";
	EdLogCnncPwd->Text = "";
	EdIstlLctnNm->Text = "";
    SePosX->Value = 0;
    SePosY->Value = 0;
	EdIP->Text = "";
	EdPort->Text = "";
	CbMnfcCmpyCd->ItemIndex = 0;

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

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

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

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

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

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

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

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

    if (!AObj) return;

    if (AMoveObj)
    {
        sJs.printf(L"selectLayerObject(%d, '%s', %d)", FLayerIdx, AObj->DSRC_CTLR_NMBR.c_str(), FRAMEOpenMap1->MapZoom);
        FRAMEOpenMap1->ExecScript(sJs);
    }
    EdId->Text = AObj->DSRC_CTLR_NMBR;
    EdRseId->Text = AObj->DSRC_CTLR_ID;
    EdRoadSpotId->Text = AObj->ROAD_SPOT_ID;
    EdLogCnncId->Text = AObj->LOG_CNNC_ID;
    EdLogCnncPwd->Text = AObj->LOG_CNNC_PW;
    EdIstlLctnNm->Text = AObj->ISTL_LCTN_NM;
    SePosX->Value = AObj->X_CRDN;
    SePosY->Value = AObj->Y_CRDN;
    EdIP->Text = AObj->CTLR_IP;
    EdPort->Text = String(AObj->CTLR_PORT);
    SeCLCT_ABNR_BASI->Value = AObj->CLCT_ABNR_BASI;

    SeAbnrAll->Value = SeCLCT_ABNR_BASI->Value;

    CMM_SetComboBoxItem(CbMnfcCmpyCd, AObj->MNFC_CMPY_CD);

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

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

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

    String arrObj = "";
    String sTemp;

    TItsFacility *pFacility;

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

void __fastcall TDSRM010M::BtnEditClick(TObject *Sender)
{
    String sId = EdId->Text;
    TItsDsrc *pObj = FRAMEDsrcList1->MyItsDsrcManager->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->DSRC_CTLR_NMBR.c_str());
            FRAMEOpenMap1->ExecScript(sJs);
        }
    }
    else
    {
        //편집모드 취소
        ChangeEditMode(1);
        if (pObj)
        {
            //원래 정보를 화면에 표출
            CMM_SetGridRow(FRAMEDsrcList1->CxList, FRAMEDsrcList1->TvList, sId, FRAMEDsrcList1->Column01->Index);
            DisplayInfo(pObj, false);

#if 0
            //지도시설물아이콘을 원래아이콘으로 변경
            sJs.printf(L"editFacilityObject(%d, %s, 0, 0)", FLayerIdx, pObj->DSRC_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 TDSRM010M::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)
    {
        FRAMEDsrcList1->CxList->Enabled = false;
    }
    else
    {
        FRAMEDsrcList1->CxList->Enabled = true;
    }

    PnlEdit->Enabled = EditMode;

#if 1
	EdId->Properties->ReadOnly = bEnabled;
	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 TDSRM010M::BtnInsertClick(TObject *Sender)
{
    FormInit();
    //신규아이디를 얻어와서 화면을 초기화한다.

    String sRseId;
    if (!FRAMEDsrcList1->MyItsDsrcManager->GetNextDsrcId(sRseId))
    {
        Application->MessageBox(L"새로운 DSRC ID를 생성하지 못하였습니다.\r\n프로그램 종료후에 다시 시도해 보세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    EdId->Text = sRseId;
    EdRseId->Text = sRseId;

    SePosX->Value = FRAMEOpenMap1->CenterX;
    SePosY->Value = FRAMEOpenMap1->CenterY;

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

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

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

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

    String sId = EdId->Text;

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

    String sMsg;
    sMsg = "ID: " + sId;
    sMsg+= "\r\n선택하신 DSRC 정보를 삭제하시겠습니까?";

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

	TItsDsrc *pObj = FRAMEDsrcList1->MyItsDsrcManager->FLists.Find(sId);

	if (pObj)
	{
		if (FRAMEDsrcList1->MyItsDsrcManager->DeleteDsrc(pObj))
		{
            pObj->DEL_YN = "Y";
            FRAMEDsrcList1->UpdateList();
            UpdateIcon();
		}

        FUpdate = true;
#if 0
		TItsFacility *pFacility = ItsFacilityManager->FLists.Find(sId);
        if (pFacility)
        {
            FUpdate = true;
        }
#endif

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

        FormInit();
        ChangeEditMode(1);

        UpdateIcon();

        //POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_14, 0);
	}
}
//---------------------------------------------------------------------------

void __fastcall TDSRM010M::BtnSaveClick(TObject *Sender)
{
	if (EdId->Text.IsEmpty()         ||
        EdRseId->Text.Trim().IsEmpty()      ||
        EdRoadSpotId->Text.IsEmpty() ||
        SePosX->Value == 0           ||
        SePosY->Value == 0           ||
        CbMnfcCmpyCd->Text.IsEmpty()  )
	{
        Application->MessageBox(L"★항목은 필수 입력 항목입니다.\r\n모두 입력후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    String sId = EdId->Text;
    String sDsrcId = EdRseId->Text.Trim();

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

    FRAMEDsrcList1->MyItsDsrcManager->FLists.Lock();
    FOR_STL(TItsDsrc*, pTmpObj, FRAMEDsrcList1->MyItsDsrcManager->FLists)
    {
        if (pTmpObj->DEL_YN == "Y") continue;
        if (pTmpObj->DSRC_CTLR_NMBR == sId) continue; //자기자신

        if (pTmpObj->DSRC_CTLR_ID == sDsrcId)
        {
            Application->MessageBox(L"DSRC ID가 이미 사용 중입니다. DSRC ID를 확인하세요.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            FRAMEDsrcList1->MyItsDsrcManager->FLists.UnLock();
            return;
        }
    }
    FRAMEDsrcList1->MyItsDsrcManager->FLists.UnLock();

    TItsDsrc *pObj;
    if (FNewDb)
        pObj = new TItsDsrc();
    else
        pObj = FRAMEDsrcList1->MyItsDsrcManager->FLists.Find(sId);

    if (pObj)
    {
        pObj->DSRC_CTLR_NMBR = sId;

        String sOldRseId = pObj->DSRC_CTLR_ID;

        pObj->DSRC_CTLR_ID       = EdRseId->Text.Trim();
        pObj->ROAD_SPOT_ID = EdRoadSpotId->Text.Trim();
        pObj->LOG_CNNC_ID  = EdLogCnncId->Text.Trim();
        pObj->LOG_CNNC_PW  = EdLogCnncPwd->Text.Trim();
        pObj->ISTL_LCTN_NM = EdIstlLctnNm->Text.Trim();
        pObj->X_CRDN       = SePosX->Value;
        pObj->Y_CRDN       = SePosY->Value;
        pObj->CTLR_IP      = EdIP->Text.Trim();
        pObj->CTLR_PORT    = EdPort->Text.Trim().ToIntDef(0);
        pObj->MNFC_CMPY_CD = ITSUtil_GetCode(CbMnfcCmpyCd->Text);
        pObj->CLCT_ABNR_BASI = (SeCLCT_ABNR_BASI->Value);

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

        bool bResult;
        if (FNewDb)
        {
            pObj->DEL_YN = "N";
            bResult = FRAMEDsrcList1->MyItsDsrcManager->InsertDsrc(pObj);
            if (bResult)
            {
                FRAMEDsrcList1->MyItsDsrcManager->FLists.Push(sId, pObj);
            }
		}
        else
		{
            bResult = FRAMEDsrcList1->MyItsDsrcManager->UpdateDsrc(sOldRseId, pObj);
		}

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

            FUpdate = true;

            FRAMEDsrcList1->UpdateList();
            UpdateIcon();
            CMM_SetGridRow(FRAMEDsrcList1->CxList, FRAMEDsrcList1->TvList, sId, FRAMEDsrcList1->Column01->Index);
            DisplayInfo(pObj, true);

            //POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_14, 0);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRM010M::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;
    DisplayInfo(pObj, true);
}
//---------------------------------------------------------------------------

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

void __fastcall TDSRM010M::BtnSaveAllClick(TObject *Sender)
{
    String sMsg;
    sMsg = "";
    sMsg+= "\r\n수집 이상 기준 정보를 전체 적용 하시겠습니까?";

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

    int nCLCT_ABNR_BASI = (SeAbnrAll->Value);
    if (FRAMEDsrcList1->MyItsDsrcManager->UpdateClctAbnrBasi(nCLCT_ABNR_BASI))
	{
        SeCLCT_ABNR_BASI->Value = SeAbnrAll->Value;
        FUpdate = true;

        Application->MessageBox(FrmLang->lblDbSave->Caption.c_str(),//L"수집 이상 기준\r\n수집 이상 기준 정보를 저장 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
	}
}
//---------------------------------------------------------------------------

void __fastcall TDSRM010M::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)
    {
    }
}
//---------------------------------------------------------------------------

