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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "ITSLangTransF.h"
#include "ITSMapF.h"
#include "CDSCodeF.h"
#include "CDSFacilityF.h"
#include "CDSNodeF.h"
#include "CDSLinkF.h"
#include "CDSCctvCtlrF.h"
#include "WindowMsgF.h"
#include "ITS_OPLibF.h"
#pragma hdrstop

#include "CTVM200MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxDropDownEdit"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinBlack"
#pragma link "dxSkinMcSkin"
#pragma link "FRAME_CctvListF"
#pragma link "cxButtonEdit"
#pragma link "cxCheckBox"
#pragma resource "*.dfm"

TCTVM200M *CTVM200M = NULL;
//---------------------------------------------------------------------------

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

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

    FRAMECctvList1->PnlTop->Visible = false;
    FRAMECctvList1->PnlBottom->Visible = false;
    FRAMECctvList1->ColumnSel->Visible = false;

    FRAMECctvList1->Column04->Visible  = false;
    FRAMECctvList1->Column06->Visible  = false;
    FRAMECctvList1->Column06->Visible  = false;
    FRAMECctvList1->Column06->Visible  = false;

    FRAMECctvList1->Column14->Visible  = true;  //대체이미지
    FRAMECctvList1->Column13->Options->Editing = false;
    FRAMECctvList1->Column14->Options->Editing = false;

    m_pGDC = FRAMECctvList1->TvList->DataController;

    FLayerIdx = LyrTp_Cctv;

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

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

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

    //APP_FillCode(CbType, "WCAM");

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

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

void __fastcall TCTVM200M::FormInit()
{
	EdNmbr->Text = "";
    EdCtlrId->Text = "";
	EdCtlrNm->Text = "";
    ISTL_LCTN_NM->Text = "";
    ISTL_LCTN_ADDR->Text = "";

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

    EdCtlrIp->Text = "";
    EdCmncPort->Text = "0";
    Se_CCTV_CTLR_PORT->Value = 0;

    Se_TYPE->Value = 1;

    Ed_CCTV_ENCD_IP->Text = ""; //인코드 IP
    Ed_CCTV_CAPT_IP->Text = ""; //자막기 IP

    Ed_STRM_SESN_NM->Text   = "";

    Ed_STRM_RTSP_ADDR->Text = "";
    Ed_STRM_RTMP_ADDR->Text = "";
	Ed_STRM_HTTP_ADDR->Text = "";
    Ed_INTR_RTMP_ADDR->Text = "";

    Ed_LINK_ID->Text        = "";
    EdTmpLinkId->Text       = "";

    ChkAll->Checked = false;
    EdImageFileName->Text = "";
    try {
        ImgDspl->Picture->Bitmap->FreeImage();
        ImgDspl->Picture->Bitmap = NULL;
    } catch(...) {}

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

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

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

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

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

    FRAMECctvList1->OnCloseQuery(CanClose);
}
//---------------------------------------------------------------------------

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

    if (!AObj) return;

	EdNmbr->Text  = String(AObj->CCTV_CTLR_NMBR);
    EdCtlrId->Text = AObj->CCTV_CTLR_ID;
	EdCtlrNm->Text = AObj->CCTV_NM;
    ISTL_LCTN_NM->Text = AObj->ISTL_LCTN_NM;
    ISTL_LCTN_ADDR->Text = AObj->ISTL_LCTN_ADDR;

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

    EdCtlrIp->Text = AObj->CCTV_CTLR_IP;
    //EdCmncPort->Text = AObj->CCTV_CTLR_PORT;
    Se_CCTV_CTLR_PORT->Value = AObj->CCTV_CTLR_PORT;

    Se_TYPE->Value = AObj->CCTV_TYPE.ToIntDef(1);

    Ed_CCTV_ENCD_IP->Text = AObj->CCTV_ENCD_IP; //인코드 IP
    Ed_CCTV_CAPT_IP->Text = AObj->CCTV_CAPT_IP; //자막기 IP

    Ed_STRM_SESN_NM->Text   = AObj->STRM_SESN_NM;

    Ed_STRM_RTSP_ADDR->Text = AObj->STRM_RTSP_ADDR;
    Ed_STRM_RTMP_ADDR->Text = AObj->STRM_RTMP_ADDR;
	Ed_STRM_HTTP_ADDR->Text = AObj->STRM_HTTP_ADDR;
    Ed_INTR_RTMP_ADDR->Text = AObj->INTR_RTMP_ADDR;

    Ed_LINK_ID->Text        = AObj->LINK_ID;

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

    if (AObj->CCTV_SBST_DSPL_YN == "N")
        Cb_CCTV_SBST_DSPL_YN->ItemIndex = 0;
    else
        Cb_CCTV_SBST_DSPL_YN->ItemIndex = 1;

    ChangeEditMode(3);

    DisplayLink(AObj);
    SelDsplImage(AObj);
}
//---------------------------------------------------------------------------

void __fastcall TCTVM200M::DisplayLink(TCctvCtlr* AObj)
{
    if (!AObj) return;

    String sLinkId = AObj->LINK_ID;

    if (sLinkId != "")
    {
        sJs.printf(L"updateEditLink('%s', %d)", sLinkId.c_str(), 3);
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTVM200M::SelDsplImage(TCctvCtlr* AObj)
{
    String sQry;

    sQry = "SELECT CCTV_SBST_DSPL_YN, CCTV_SBST_IMGN \r\n"
           "  FROM TB_CCTV_CTLR                      \r\n"
           " WHERE CCTV_MNGM_NMBR = :p01               \r\n";
    try
    {
        pADO->Close();
        pADO->SQL->Clear();
        pADO->Connection = ITSDb_GetConnection();
        pADO->SQL->Text = sQry;
        pADO->Parameters->ParamByName("p01")->Value = AObj->CCTV_CTLR_NMBR;
        pADO->Prepared = true;
        pADO->Open();
    }
    catch(EDatabaseError &E)
    {
        ShowMessage(String(E.ClassName()) + E.Message);
        return;
    }

    if (pADO->RecordCount == 0)
    {
        pADO->Close();
        return;
    }

    ForceDirectories(g_sTempDir);

    TADOBlobStream *BS;
    int             nFileSize = 0;
    String          sImgFile  = g_sTempDir + "CCTVB_" + AObj->CCTV_CTLR_NMBR + ".bmp";

    try {
        ImgDspl->Picture->Bitmap->FreeImage();
        ImgDspl->Picture->Bitmap = NULL;
        DeleteFile(sImgFile);
    } catch(...) {}

    String sDispBlob = "N";
    try
    {
        sDispBlob = pADO->FieldByName("CCTV_SBST_DSPL_YN")->AsString;
        BS = (TADOBlobStream *)pADO->CreateBlobStream(pADO->FieldByName("CCTV_SBST_IMGN"), bmRead);
        BS->SaveToFile(sImgFile);
        nFileSize = BS->Size;
        delete BS;

        pADO->Close();

        if (nFileSize)
        {
            try
            {
                ImgDspl->Picture->LoadFromFile(sImgFile);
            }
            catch(Exception &E)
            {
                ShowMessage(String(E.ClassName()) + E.Message);
            }
        }
    }
    catch(Exception &E)
    {
        delete BS;
        ShowMessage(String(E.ClassName()) + E.Message);
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTVM200M::UpdateIcon()
{
}
//---------------------------------------------------------------------------

void __fastcall TCTVM200M::BtnEditClick(TObject *Sender)
{
    String sId = EdNmbr->Text;
    TCctvCtlr *pObj = CctvCtlrManager->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->CCTV_CTLR_NMBR.c_str());
        }
    }
    else
    {
        //편집모드 취소
        ChangeEditMode(1);
        if (pObj)
        {
            //원래 정보를 화면에 표출
            CMM_SetGridRow(FRAMECctvList1->CxList, FRAMECctvList1->TvList, sId, FRAMECctvList1->Column01->Index);
            DisplayInfo(pObj, false);

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

void __fastcall TCTVM200M::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)
    {
        FRAMECctvList1->CxList->Enabled = false;
    }
    else
    {
        FRAMECctvList1->CxList->Enabled = true;
    }

    PnlEdit->Enabled = EditMode;
}
//---------------------------------------------------------------------------


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

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

    EdNmbr->Text = String(nNmbr);

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

void __fastcall TCTVM200M::BtnDeleteClick(TObject *Sender)
{
    int nIdx = m_pGDC->FocusedRecordIndex;
    if (nIdx < 0) return;

    String sId = EdNmbr->Text;

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

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

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

	TCctvCtlr *pObj = CctvCtlrManager->FLists.Find(sId);

	if (pObj)
	{
		if (CctvCtlrManager->DeleteCctv(pObj))
		{
            pObj->DEL_YN = "Y";
            FRAMECctvList1->UpdateList();
            UpdateIcon();
		}

        FUpdate = true;

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

        FormInit();
        ChangeEditMode(1);

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

void __fastcall TCTVM200M::BtnSaveClick(TObject *Sender)
{
	if (EdNmbr->Text.IsEmpty())
	{
        Application->MessageBox(L"목록에서 CCTV를 선택하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    String sNmbr    = EdNmbr->Text;
    TCctvCtlr *pObj = CctvCtlrManager->FLists.Find(sNmbr);

    if (!pObj)
    {
        Application->MessageBox(L"선택하신 CCTV정보를 확인할 수 없습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    bool    bResult = false;
    String  CCTV_SBST_IMGN;
    String  CCTV_SBST_DSPL_YN = Cb_CCTV_SBST_DSPL_YN->ItemIndex == 0 ? "N" : "Y";

    TMemoryStream *dataStream = new TMemoryStream();
    try
    {
        try
        {
            ImgDspl->Picture->Bitmap->SaveToStream(dataStream);
            if (CCTV_SBST_DSPL_YN == "Y" && dataStream->Size == 0)
            {
                Application->MessageBox(L"CCTV 영상 대체이미지 정보를 설정하셔야 합니다.",
                                        FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
                return;
            }
            if (ChkAll->Checked)
            {
                sNmbr = "";
            }
            bResult = UpdateDsplInfo(sNmbr, CCTV_SBST_DSPL_YN, dataStream);
        }
        catch(Exception &e)
        {
        }
    }
    __finally
    {
        if (dataStream) delete dataStream;
        dataStream = NULL;
    }

    if (bResult)
    {
        Application->MessageBox(L"CCTV 영상 대체이미지 정보저장\r\nCCTV 영상 대체이미지 정보를 저장 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FUpdate = true;

        if (ChkAll->Checked)
        {
            CctvCtlrManager->FLists.Lock();
            FOR_STL(TCctvCtlr*, pTmpObj, CctvCtlrManager->FLists)
            {
                pTmpObj->CCTV_SBST_DSPL_YN = CCTV_SBST_DSPL_YN;
            }
            CctvCtlrManager->FLists.UnLock();
        }
        else
        {
            pObj->CCTV_SBST_DSPL_YN = CCTV_SBST_DSPL_YN;
        }

        FRAMECctvList1->UpdateList();
        UpdateIcon();
        CMM_SetGridRow(FRAMECctvList1->CxList, FRAMECctvList1->TvList, sNmbr, FRAMECctvList1->Column01->Index);
        DisplayInfo(pObj, true);
    }
}
//---------------------------------------------------------------------------
bool __fastcall TCTVM200M::UpdateDsplInfo(String ANmbr, String ADsplYn, TMemoryStream *dataStream)
{
    String sQry;
    TADOQuery *pADO = NULL;

    if (dataStream->Size == 0)
    {
        sQry = "UPDATE TB_CCTV_CTLR              \r\n"
               "   SET CCTV_SBST_DSPL_YN = :p02, \r\n"
               "       CCTV_SBST_IMGN    = NULL  \r\n";
    }
    else
    {
        sQry = "UPDATE TB_CCTV_CTLR              \r\n"
               "   SET CCTV_SBST_DSPL_YN = :p02, \r\n"
               "       CCTV_SBST_IMGN    = :p03  \r\n";
    }

    if (ANmbr != "")
    {
        sQry += " WHERE CCTV_MNGM_NMBR = :p01 \r\n";
    }

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);

            if (ANmbr != "")
            {
                ITSDb_SQLBind(pADO, "p01", ANmbr);
            }
            ITSDb_SQLBind(pADO, "p02", ADsplYn);
            if (dataStream->Size != 0)
            {
    		    pADO->Parameters->ParamByName("p03")->LoadFromStream(dataStream, ftBlob);
            }

			pADO->ExecSQL();

            return true;
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("UpdateDsplInfo", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("UpdateDsplInfo", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
    return true;
}
//---------------------------------------------------------------------------

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

void __fastcall TCTVM200M::Se_CMRA_CHNLPropertiesChange(TObject *Sender)
{
    if (((TcxSpinEdit*)Sender)->Value < ((TcxSpinEdit*)Sender)->Properties->MinValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MinValue;
    else if(((TcxSpinEdit*)Sender)->Value > ((TcxSpinEdit*)Sender)->Properties->MaxValue &&
        ((TcxSpinEdit*)Sender)->Properties->MaxValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MaxValue;
}
//---------------------------------------------------------------------------
void __fastcall TCTVM200M::UpdateEditLink()
{
    TItsNode* pNode;
    String    STRT_NM;
    String    END_NM;

    try
    {
        ItsLinkManager->FLists.Lock();
        try
        {
            FOR_STL(TItsLink*, pLink, ItsLinkManager->FLists)
            {
                if (pLink->DEL_YN == "Y")   continue;

#if 0
                pVrtx = pLink->Vrtxs.Find(nZoom);
                if (!pVrtx) continue;

                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(),
                    pVrtx->X_CRDN_ARR.c_str(),
                    pVrtx->Y_CRDN_ARR.c_str());
#else
                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());
                }
#endif
            }
        }
        __finally
        {
            ItsLinkManager->FLists.UnLock();
        }
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

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

void __fastcall TCTVM200M::BtnApplyClick(TObject *Sender)
{
    if (EditMode)
    {
        Ed_LINK_ID->Text = EdTmpLinkId->Text.Trim();
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTVM200M::EdImageFileNameClick(TObject *Sender)
{
    OpenBmp->Title    = FTitle;
    OpenBmp->FileName = "";
    OpenBmp->Execute();
}
//---------------------------------------------------------------------------
#include <jpeg.hpp>
bool APP_CheckBmpFile(String AInFileName, String &AOutFileName)
{
    String sFilePath = ExtractFilePath(AInFileName);
    String sFileName = ExtractFileName(AInFileName);
    String sFileExt  = ExtractFileExt(AInFileName);

    AOutFileName = AInFileName;
    if (sFileExt.UpperCase() == ".BMP")
    {
        return true;
    }

    AOutFileName = AInFileName + ".bmp";

    TImage *Image1 = new TImage(NULL);
    TMemoryStream *pImgStream = new TMemoryStream();
    try
    {
        try
        {
            pImgStream->LoadFromFile(AInFileName);
            sFileExt = sFileExt.UpperCase();
            if (sFileExt == ".PNG")
            {
                TdxPNGImage *img = new TdxPNGImage;
                img->LoadFromStream(pImgStream);
                Image1->Picture->Bitmap->Assign(img);
                Image1->Picture->Bitmap->PixelFormat = pf24bit;
                Image1->Picture->Bitmap->SaveToFile(AOutFileName);
                SAFE_DELETE(img);
                return true;
            }
            else
            if (sFileExt == ".JPG" || sFileExt == ".JPEG")
            {
                TJPEGImage *img = new TJPEGImage();
                img->LoadFromStream(pImgStream);
                Image1->Picture->Bitmap->Assign(img);
                Image1->Picture->Bitmap->PixelFormat = pf24bit;
                Image1->Picture->Bitmap->SaveToFile(AOutFileName);
                SAFE_DELETE(img);
                return true;
            }
        }
        catch(Exception &e)
        {
        }
    }
    __finally
    {
        SAFE_DELETE(pImgStream);
        SAFE_DELETE(Image1);
    }

    return false;
}
//---------------------------------------------------------------------------

void __fastcall TCTVM200M::OpenBmpCanClose(TObject *Sender, bool &CanClose)
{
    String sFName = OpenBmp->FileName;
    //sFName = sFName.UpperCase();

    String sFilePath = ExtractFilePath(sFName);
    String sFileName = ExtractFileName(sFName);
    String sFileExt  = ExtractFileExt(sFName);
    if (sFileExt.UpperCase() != ".BMP")
    {
        if (!APP_CheckBmpFile(sFName, sFName))
        {
            Application->MessageBox(L"이미지 파일을 읽어오는데 실패하였습니다", L"이미지 파일 읽기 실패", MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }
        sFileExt = ExtractFileExt(sFName);
    }

	String sMsgTitle, sMsgString;

    sMsgTitle = "CCTV 대체 이미지 선택";
    sFName = sFName.UpperCase();
	if (sFName.SubString(sFName.Length()-2, 3) != "BMP")
    {
        sMsgString = "BMP 파일만 적용 가능합니다.";
        Application->MessageBox(sMsgString.c_str(), sMsgTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
		return;
	}

    try
    {
        int nFileSize = ITSUtil_GetFileSize(sFName);
        if (nFileSize <= 0)
        {
            sMsgString = "이미지 파일을 읽어 오는데 실패하였습니다.";
            Application->MessageBox(sMsgString.c_str(), sMsgTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
            return;
        }
#if 0
        if (nFileSize > (1024 * 32))   // Max 32Kbytes
        {
            sMsgString = "이미지 파일의 최대 크기는 32KBytes를 넘을 수 없습니다.\r\n이미지 파일의 용량을 줄여 주세요.";
            Application->MessageBox(sMsgString.c_str(), sMsgTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
            return;
        }
#endif

        //EdImageSize->Text = String(dwFileSize);//GetFileSize(sFName));

        EdImageFileName->Text = sFName;
        ImgDspl->Picture->Bitmap->FreeImage();
        ImgDspl->Picture->Bitmap = NULL;
        ImgDspl->Picture->Bitmap->LoadFromFile(sFName);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTVM200M::BtnClearClick(TObject *Sender)
{
    EdImageFileName->Text = "";
    ImgDspl->Picture->Bitmap->FreeImage();
    ImgDspl->Picture->Bitmap = NULL;
}
//---------------------------------------------------------------------------

