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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "CDSCodeF.h"
#include "CDSFacilityF.h"
#pragma hdrstop

#include "DSRM010MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "FRAME_DsrcListF"
#pragma link "FRAME_FlashMapF"
#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 resource "*.dfm"

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

void TDSRM010M_FlashCall(TObject *ASender, const WideString request)
{
    try
    {
        if (!DSRM010M) return;
        DSRM010M->ShockwaveFlash1FlashCall1(ASender, request);
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

__fastcall TDSRM010M::TDSRM010M(TComponent* Owner)
    : TForm(Owner)
{
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FUpdate= false;
    FTitle = "DSRC-RSE 관리";

    MapStart = false;

    FRAMEGisMap1->FlashCallbackFunc = TDSRM010M_FlashCall;
    FRAMEGisMap1->DrawMode = 1; //구간정보표출

    FRAMEGisMap1->ImgPan->Visible = true;
    FRAMEGisMap1->ImgZoomIn->Visible = true;
    FRAMEGisMap1->ImgZoomOut->Visible = true;
    FRAMEGisMap1->ImgSel->Visible = true;
    FRAMEGisMap1->ImgStnd->Visible = true;
    FRAMEGisMap1->ImgRefresh->Visible = true;

    FRAMEGisMap1->LbDef->Caption = "(선택메뉴를 클릭하여 위치를 선택합니다.)";
    FRAMEGisMap1->LbDef->Hint = FRAMEGisMap1->LbDef->Caption;
    FRAMEGisMap1->LbDef->Visible = true;

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


    m_pGDC = FRAMEDsrcList1->TvList->DataController;
}
//---------------------------------------------------------------------------

/*
 * 닫기버튼 이나 x버튼 클릭시 공통으로 처리하는 로직이들어간다..
 * Form과 DataModule class를 delete시킨다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TDSRM010M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

/*
 * Form을 보여줄때 호출되는 event 메서드이다.
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TDSRM010M::FormShow(TObject *Sender)
{
    Refresh();

    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;

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

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
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;
}
//---------------------------------------------------------------------------

/*
 * Form이 Show되고 난 후 최초 1회 수행되는 타이머 이벤트
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TDSRM010M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;

    FRAMEGisMap1->LinkLevel = 2;
    FRAMEGisMap1->LoadGisMap();

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

/*
 * Close 버튼 클릭 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
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);
}
//---------------------------------------------------------------------------

void __fastcall TDSRM010M::DisplayInfo(TItsDsrc* AObj)
{
    FormInit();

    if (!AObj) return;

    EdId->Text = AObj->ID;
    EdRseId->Text = AObj->RSE_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 = StrToFloatDef(AObj->LCTN_X, 0);
    SePosY->Value = StrToFloatDef(AObj->LCTN_Y, 0);
    EdIP->Text = AObj->IP;
    EdPort->Text = AObj->PORT;
    SeCLCT_ABNR_BASI->Value = AObj->CLCT_ABNR_BASI;

    SeAbnrAll->Value = SeCLCT_ABNR_BASI->Value;

    CMM_SetComboBoxItem(CbMnfcCmpyCd, AObj->MNFC_CMPY_CD);

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

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

void __fastcall TDSRM010M::UpdateRseIcon()
{
    if (!MapStart) return;

    TItsFacility *pFacility;
    try
    {
        TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "RemoveFacility", FAC_RSE);

        //if (ChkViewIcon->Checked)
        {
            String sObjList = "";

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

                    String sLoc = TCommFlash::ReplaceName(pObj->ISTL_LCTN_NM);
                    sObjList += (pObj->ID + "," + "0," + sLoc + "," + pObj->LCTN_X + "," + pObj->LCTN_Y + "," + pObj->RSE_ID + "|");
                }
            }
            __finally
            {
                FRAMEDsrcList1->MyItsDsrcManager->FLists.UnLock();

                if (sObjList != "")
                {
                    sObjList = sObjList.SubString(1, sObjList.Length()-1);
                    TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "AddFacility", FAC_RSE + "|" + sObjList);
                }
            }
        }
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TDSRM010M::ChkViewIconClick(TObject *Sender)
{
    if (!FRAMEGisMap1->MapStart) return;
    String sShowIcon = ChkViewIcon->Checked ? "1" : "0";
    String sShowName = ChkViewName->Checked ? "1" : "0";
    TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "ShowFacility", "RSE|" + sShowIcon + "|" + sShowName);
}
//---------------------------------------------------------------------------

void __fastcall TDSRM010M::BtnEditClick(TObject *Sender)
{
    if (BtnEdit->Caption == "편집")
    {
        ChangeEditMode(0);
        FNewDb = false;
    }
    else
    {
        String sId = EdId->Text;
        ChangeEditMode(1);

        TItsDsrc *pObj = FRAMEDsrcList1->MyItsDsrcManager->FLists.Find(sId);
        if (pObj)
        {
            CMM_SetGridRow(FRAMEDsrcList1->CxList, FRAMEDsrcList1->TvList, sId, FRAMEDsrcList1->Column01->Index);
            DisplayInfo(pObj);
        }
    }
}
//---------------------------------------------------------------------------

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;//데이터 편집 취소";
        }
        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;
        }
        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;//데이터 편집 취소";
        }
        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;
        }
        break;
    }

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

#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->GetNextRseId(sRseId))
    {
        Application->MessageBox(L"새로운 RSE ID를 생성하지 못하였습니다.\r\n프로그램 종료후에 다시 시도해 보세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    EdId->Text = sRseId;
    EdRseId->Text = sRseId;
    ChangeEditMode(2);
    FNewDb = true;
}
//---------------------------------------------------------------------------

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

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

    String sId = EdId->Text;

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

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

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

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

        FormInit();
        ChangeEditMode(1);

        //UpdateRseIcon();
        TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "DeleteFacility", FAC_RSE + "|" + sId);

        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;

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

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

        String sOldRseId = pObj->RSE_ID;

        pObj->RSE_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->LCTN_X       = VarToStr(SePosX->Value);
        pObj->LCTN_Y       = VarToStr(SePosY->Value);
        pObj->IP           = EdIP->Text.Trim();
        pObj->PORT         = EdPort->Text.Trim();
        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-RSE 정보저장\r\nDSRC-RSE 정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

            FUpdate = true;

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

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

void __fastcall TDSRM010M::ShockwaveFlash1FlashCall1(TObject *ASender, const WideString request)
{
    try
    {
        String sTemp;
        String sFunc;
        String sArgs;

        sTemp = request;

        int nFuncStrIdx = sTemp.Pos("\"");
        int nFuncEndIdx = sTemp.Pos("\" returntype");
        int nArgsStrIdx = sTemp.Pos("string>");
        int nArgsEndIdx = sTemp.Pos("</string");

        sFunc = sTemp.SubString(nFuncStrIdx + 1, nFuncEndIdx - (nFuncStrIdx + 1));
        sArgs = sTemp.SubString(nArgsStrIdx + 7, nArgsEndIdx - (nArgsStrIdx + 7));

        if (sFunc == "OnMapStart")
        {
            String sShowIcon = ChkViewIcon->Checked ? "1" : "0";
            String sShowName = ChkViewName->Checked ? "1" : "0";
            MapStart = true;
            TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "ShowFacility", "RSE|" + sShowIcon + "|" + sShowName);
        }
        else
        if (sFunc == "OnDrawTrafLink")
        {
            static bool bFirst = true;
            if (bFirst)
            {
                UpdateRseIcon();
                bFirst = true;
            }
        }
        else
        if (sFunc == "OnMousePos")
        {
            if (FRAMEGisMap1->ModeSelect)
            {
                TStringList *pStringList = new TStringList;
                pStringList->CommaText = sArgs;
                String sMapX = pStringList->Strings[0]; //lat
                String sMapY = pStringList->Strings[1]; //lng
                delete pStringList;
                try {
                    SePosX->Value = sMapX.ToDouble();
                    SePosY->Value = sMapY.ToDouble();
                } catch(...) {}
            }
        }
        else
        if (sFunc == "OnSelLink")
        {
            if (FRAMEGisMap1->ModeSelect)
            {
                TStringList *pStringList = new TStringList;
                pStringList->CommaText = sArgs;

                String sLevl = pStringList->Strings[0]; //링크레벨
                String sId   = pStringList->Strings[1]; //링크아이디
                String sZoom = pStringList->Strings[2]; //줌레벨
                String sPosX = pStringList->Strings[3]; //x
                String sPosY = pStringList->Strings[4]; //y
                String sMapX = pStringList->Strings[5]; //lat
                String sMapY = pStringList->Strings[6]; //lng

                delete pStringList;

                try {
                    SePosX->Value = sMapX.ToDouble();
                    SePosY->Value = sMapY.ToDouble();
                } catch(...) {}
            }
        }
        else
        if (sFunc == "OnClickFacility")
        {
            TStringList *pStringList = new TStringList;
            pStringList->CommaText = sArgs;

            String sType = pStringList->Strings[0]; //유형
            String sId   = pStringList->Strings[1]; //아이디
            String sName = pStringList->Strings[2]; //아이디

            delete pStringList;
        }
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

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

