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

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

#include "VMSM420MF.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 "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 "cxImage"
#pragma link "cxButtonEdit"
#pragma link "cxBlobEdit"
#pragma resource "*.dfm"

TVMSM420M *VMSM420M = NULL;
//---------------------------------------------------------------------------

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

    FUpdate= false;
    FTitle = Caption;//"VMS 소통정보 이미지관리";

	FListSymb = new TList;

    EditMode = false;
    FIsUpdate = false;

    TvList->OptionsView->DataRowHeight  = 0;
    TvList->OptionsView->CellAutoHeight = true;
    TvList->OptionsView->Indicator      = false;

    TvList->OptionsCustomize->ColumnMoving  = false;
    TvList->OptionsCustomize->ColumnSorting = false;

    TvList->Columns[0]->Width = 60;
    TvList->Columns[0]->Options->HorzSizing = false;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::CommClose()
{
    try
    {
        ClearSymbloList();
        SAFE_DELETE(FListSymb);
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::FormShow(TObject *Sender)
{
    lblImgSize->Caption = "";
    Refresh();

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

void __fastcall TVMSM420M::FormInit()
{
	EdNmbr->Text = "";
    EdExpl->Text = "";
    EdImageFileName->Text = "";

    lblImgSize->Caption = "";
    ImgPreView->Picture->Bitmap->FreeImage();
    ImgPreView->Picture->Bitmap = NULL;

    ImgTemp->Picture->Bitmap->FreeImage();
    ImgTemp->Picture->Bitmap = NULL;

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

    CMM_ClearGridTableView(TvImageCell);

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

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

    LoadImageSymbol();
}
//---------------------------------------------------------------------------

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

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

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

void __fastcall TVMSM420M::DisplayInfo()
{
    FormInit();

	int nRow = TvList->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

	TcxGridDataController *pDc = TvList->DataController;

	nRow = pDc->FocusedRecordIndex;
    if (nRow < FListSymb->Count)
    {
        Graphics::TBitmap *bitmap = (Graphics::TBitmap*)FListSymb->Items[nRow];
        ImgPreView->Picture->Bitmap->Assign(bitmap);
        ImgTemp->Picture->Bitmap->Assign(bitmap);

        FOldWidth  = bitmap->Width;
        FOldHeight = bitmap->Height;
        lblImgSize->Caption = String(bitmap->Width) + " * " + String(bitmap->Height);
    }

    EdNmbr->Text  = VarToStr(pDc->Values[nRow][ColLink1->Index]);
    EdExpl->Text  = VarToStr(pDc->Values[nRow][ColLink3->Index]);
    EdVmsCd->Text = VarToStr(pDc->Values[nRow][ColLink4->Index]);

    //셀정보 업데이트
    LoadImageSymbolCell(EdNmbr->Text);
    UpdateCellColor();

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

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

        if (CMM_FindGridData(TvList->DataController, sId, ColLink1->Index) >= 0)
        {
            CMM_SetGridRow(CxList, TvList, sId, ColLink1->Index);
            DisplayInfo();
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::ChangeEditMode(int AEdit)
{
    FImageUpdate = false;
    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;
            EdImageFileName->Enabled = FIsUpdate;
        }
        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;
            EdImageFileName->Enabled = 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;
            EdImageFileName->Enabled = 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;
            EdImageFileName->Enabled = FIsUpdate;
        }
        break;
    }

    BtnSaveImgFile->Enabled = false;
    if (ImgPreView->Picture->Bitmap != NULL)
    {
        if (ImgPreView->Picture->Bitmap->Height != 0)
        {
            BtnSaveImgFile->Enabled = true;
        }
    }
    if (AEdit == 0 || AEdit == 2)
    {
        PnlCmd->Enabled = true;
        GrpList->Enabled = false;
    }
    else
    {
        PnlCmd->Enabled = false;
        GrpList->Enabled = true;
    }

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

bool __fastcall TVMSM420M::UpdateVmsImage(String ANmbr, String AExpl)
{
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "UPDATE TB_VMS_SYMB_LIB                                    \r\n"
           "   SET RGST_DT   = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'),  \r\n"
           "       SYMB_EXPL = :p02,                                  \r\n"
           "       IMAG_DATA = :p03,                                  \r\n"
           "       UPDT_DT   = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS')   \r\n"
           " WHERE SYMBLIB_NMBR = :p01                                \r\n";

	TMemoryStream *dataStream = new TMemoryStream();
   	//ImgPreView->Picture->Bitmap->SaveToStream(dataStream);
   	ImgTemp->Picture->Bitmap->SaveToStream(dataStream);

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

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", ANmbr);
            ITSDb_SQLBind(pADO, "p02", AExpl);
    		pADO->Parameters->ParamByName("p03")->LoadFromStream(dataStream, ftBlob);
			pADO->ExecSQL();

            if (FImageUpdate)
            {
    sQry = "UPDATE TB_VMS_FORM_OBJECT    \r\n"
           "   SET VMS_DSPL_FIGR = :p03  \r\n"
           " WHERE SYMBLIB_NMBR = :p01   \r\n";

                ITSDb_SQLText(pADO, sQry);
                ITSDb_SQLBind(pADO, "p01", ANmbr);
                pADO->Parameters->ParamByName("p03")->LoadFromStream(dataStream, ftBlob);
                pADO->ExecSQL();

    //통신서버가 항상 폼정보를 내려보내도록 업데이트시각을 업데이트한다.
    sQry = "UPDATE TB_VMS_FORM                                      \r\n"
           "   SET UPDT_DT = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS')   \r\n"
           " WHERE VMS_FORM_ID IN (SELECT VMS_FORM_ID               \r\n"
           "                         FROM TB_VMS_FORM_OBJECT        \r\n"
           "                        WHERE SYMBLIB_NMBR = :p01       \r\n"
           "                        GROUP BY VMS_FORM_ID)           \r\n";

                ITSDb_SQLText(pADO, sQry);
                ITSDb_SQLBind(pADO, "p01", ANmbr);
                pADO->ExecSQL();

                //폼이미지를 새로생성
                FrmLang->UpdateVmsFormImage(ANmbr, FOldWidth, FOldHeight, FNewWidth, FNewHeight);

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

                CComm_VmsFormUpdate();
            }

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

bool __fastcall TVMSM420M::InsertVmsImage(String ANmbr, String AExpl, String AFileName, String ATypeCd)
{
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "INSERT INTO TB_VMS_SYMB_LIB(SYMBLIB_NMBR, RGST_DT, SYMB_EXPL, IMAG_DATA, SYMB_FILE_NM, SYMB_TYPE, AVI_DATA, IMAG_SIZE, UPDT_DT, DEL_YN) \r\n"
           "                     VALUES(:p01,         :p02,    :p03,      :p04,      NULL,         :p05,      NULL,     :p06,      :p07,    'N'   ) \r\n";

	TMemoryStream *dataStream = new TMemoryStream();
   	//ImgPreView->Picture->Bitmap->SaveToStream(dataStream);
   	ImgTemp->Picture->Bitmap->SaveToStream(dataStream);

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

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", ANmbr);
            ITSDb_SQLBind(pADO, "p02", Now().FormatString("yyyymmddhhnnss"));
            ITSDb_SQLBind(pADO, "p03", AExpl);

    		pADO->Parameters->ParamByName("p04")->LoadFromStream(dataStream, ftBlob);

            ITSDb_SQLBind(pADO, "p05", ATypeCd);
            ITSDb_SQLBind(pADO, "p06", FFileSize);
            ITSDb_SQLBind(pADO, "p07", Now().FormatString("yyyymmddhhnnss"));
			pADO->ExecSQL();
            return true;
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("VMS image update", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("VMS image update", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        if (dataStream) delete dataStream;
        dataStream = NULL;
    }
    return true;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::BtnSaveClick(TObject *Sender)
{
	if (EdNmbr->Text.IsEmpty())
	{
        Application->MessageBox(FrmLang->lblImage1->Caption.c_str(),//L"VMS 이미지정보 저장\r\n이미지 번호를 입력하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}
	if (EdExpl->Text.Trim().IsEmpty())
	{
        Application->MessageBox(FrmLang->lblImage2->Caption.c_str(),//L"VMS 이미지정보 저장\r\n이미지 설명을 입력하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    String sNmbr = EdNmbr->Text;
    String sExpl = EdExpl->Text.Trim();

    if (TvImageCell->DataController->RecordCount == 0)
    {
        Application->MessageBox(lblText1->Caption.c_str(),//L"VMS 이미지정보 저장\r\n이미지 좌표 정보가 없습니다.\r\n이미지 이미지를 클릭하여 이미지 좌표를 설정하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
#if 0
        String sMsg;
        sMsg = FrmLang->lblImage7->Caption + ": " + sNmbr;//"VMS이미지번호: " + sNmbr;
        sMsg+= "\r\n" + lblText2->Caption;//"이미지 좌표 정보가 없습니다.\r\n소통정보 이미지 정보를 저장하시겠습니까?";

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

    bool bResult = false;

    if (!FNewDb)
    {
        bResult = UpdateVmsImage(sNmbr, sExpl);
    }
    else
    {
        if (EdImageFileName->Text.Trim().IsEmpty())
        {
            Application->MessageBox(FrmLang->lblImage3->Caption.c_str(),//L"VMS 이미지정보 저장\r\n이미지를 선택하셔야 합니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }
        bResult = InsertVmsImage(sNmbr, sExpl, "", "SBT2");
    }

    if (!bResult) return;


    String ANmbr = sNmbr;

    String sQry;
    TADOQuery *pADO = NULL;

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

    sQry = "DELETE TB_VMS_SYMB_IFSC       \r\n"
           " WHERE SYMBLIB_NMBR = :p01    \r\n";

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", ANmbr);
			pADO->ExecSQL();

    sQry = "INSERT INTO TB_VMS_SYMB_IFSC (     \r\n"
           "           SYMBLIB_NMBR,           \r\n"
           "           CELL_ID,                \r\n"
           "           POSX,                   \r\n"
           "           POSY,                   \r\n"
           "           VMS_IFSC_ID)            \r\n"
           "  VALUES (                         \r\n"
           "           :p01,                   \r\n"
           "           :p02,                   \r\n"
           "           :p03,                   \r\n"
           "           :p04,                   \r\n"
           "           :p05 )                  \r\n";

            ITSDb_SQLText(pADO, sQry);

            ITSDb_GetConnection()->BeginTrans();

            TcxGridDataController *pGDC = TvImageCell->DataController;
            int nRows = pGDC->RecordCount;
            for (int ii = 0; ii < nRows; ii++)
            {
                String sCellId = VarToStr(pGDC->Values[ii][ColCellId->Index]);
                String sPosX   = VarToStr(pGDC->Values[ii][ColCellPosX->Index]);
                String sPosY   = VarToStr(pGDC->Values[ii][ColCellPosY->Index]);
                String sIfscId = VarToStr(pGDC->Values[ii][ColIfscId->Index]);

                ITSDb_SQLBind(pADO, "p01", ANmbr);
                ITSDb_SQLBind(pADO, "p02", sCellId);
                ITSDb_SQLBind(pADO, "p03", sPosX);
                ITSDb_SQLBind(pADO, "p04", sPosY);
                ITSDb_SQLBind(pADO, "p05", sIfscId);

                ITSDb_SQLExec(pADO);
            }

            ITSDb_GetConnection()->CommitTrans();
            bResult = true;
        }
        catch(EDatabaseError &E)
        {
            ITSDb_GetConnection()->RollbackTrans();
            DBERRORMSG("VMS image cell save", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            ITSDb_GetConnection()->RollbackTrans();
            DBERRORMSG("VMS image cell save", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    if (bResult)
    {
        Application->MessageBox(lblText3->Caption.c_str(),//L"VMS 소통정보 이미지정보 저장\r\nVMS 소통정보 이미지정보를 저장 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FUpdate = true;

        LoadImageSymbol();
        CMM_SetGridRow(CxList, TvList, sNmbr, ColLink1->Index);
        DisplayInfo();

        CComm_VmsImageTrafficUpdate();  // VMS서버로 이미지가 업데이트 되었음을 알린다.

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

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

    int nNmbr;

    if (!FrmLang->GetNextVmsImgeId(nNmbr, 8000, 8999))
    {
        Application->MessageBox(FrmLang->lblImage4->Caption.c_str(),//L"새로운 VMS 이미지정보를 생성하지 못하였습니다.\r\n프로그램 종료후에 다시 시도해 보세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    EdNmbr->Text = String(nNmbr);

    ChangeEditMode(2);
    FNewDb = true;
    EdImageFileNameClick((TObject *)EdImageFileName);
}
//---------------------------------------------------------------------------

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

    String sId = EdNmbr->Text;

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

    if (FrmLang->CheckImageUseCount(sId) > 0)
    {
        Application->MessageBox(FrmLang->lblImage5->Caption.c_str(),//L"삭제할 이미지가 VMS 폼에서 사용되고 있습니다.\r\n먼저 해당 폼에서 삭제해주시기 바랍니다.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    String sMsg;
    sMsg = FrmLang->lblImage7->Caption + ": " + sId;//"VMS이미지번호: " + sId;
    sMsg+= "\r\n" + FrmLang->lblImage8->Caption;//"선택하신 VMS 이미지 정보를 삭제하시겠습니까?";

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

    if (FrmLang->DelVmsImage(sId, true))
    {
        FUpdate = true;

        Application->MessageBox(FrmLang->lblImage9->Caption.c_str(),//L"VMS 이미지정보삭제\r\nVMS 이미지정보를 삭제 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FormInit();
        ChangeEditMode(1);

        LoadImageSymbol();

        CComm_VmsImageTrafficUpdate();  // VMS서버로 이미지가 업데이트 되었음을 알린다.

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

void __fastcall TVMSM420M::BtnSaveImgFileClick(TObject *Sender)
{
    SaveDialog->Title      = FTitle;
    SaveDialog->InitialDir = ExtractFilePath(Application->ExeName);
    SaveDialog->Filter     = "Bitmap image Files (*.bmp)|*.bmp";
    SaveDialog->FileName   = EdNmbr->Text + ".bmp";

    if (SaveDialog->Execute())
    {
        try {
            String sFileName = SaveDialog->FileName;

            int iRet = sFileName.Pos(".bmp");
            if (iRet == 0)
            {
                sFileName = SaveDialog->FileName + ".bmp";
            }

            //ImgPreView->Picture->SaveToFile(sFileName);
            ImgTemp->Picture->SaveToFile(sFileName);
        }
        catch (Exception &exception)
        {
            Application->ShowException(&exception);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::EdImageFileNameClick(TObject *Sender)
{
    OpenBmp->Title    = FTitle;
    OpenBmp->FileName = "";
    OpenBmp->Execute();
}
//---------------------------------------------------------------------------

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

	String sMsgTitle, sMsgString;

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

    try
    {
        FFileSize = ITSUtil_GetFileSize(sFName);
        if (FFileSize <= 0)
        {
            sMsgString = FrmLang->lblImage12->Caption;//"이미지 파일을 읽어 오는데 실패하였습니다.";
            Application->MessageBox(sMsgString.c_str(), sMsgTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
            return;
        }
#if 0
        if (FFileSize > (1024 * 32))   // Max 32Kbytes
        {
            sMsgString = FrmLang->lblImage13->Caption;//"이미지 파일의 최대 크기는 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;
        ImgPreView->Picture->Bitmap->FreeImage();
        ImgPreView->Picture->Bitmap = NULL;
        ImgPreView->Picture->Bitmap->LoadFromFile(sFName);

        lblImgSize->Caption = String(ImgPreView->Picture->Bitmap->Width) + " * " + String(ImgPreView->Picture->Bitmap->Height);

        ImgTemp->Picture->Bitmap->FreeImage();
        ImgTemp->Picture->Bitmap = NULL;
        ImgTemp->Picture->Bitmap->LoadFromFile(sFName);

        FNewWidth  = ImgTemp->Picture->Bitmap->Width;
        FNewHeight = ImgTemp->Picture->Bitmap->Height;

        FImageUpdate = true;
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::ClearSymbloList()
{
	for(int ii = 0; ii < FListSymb->Count; ii++)
	{
		Graphics::TBitmap *bitmap = (Graphics::TBitmap *)FListSymb->Items[ii];
		delete bitmap;
	}
	FListSymb->Clear();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::LoadImageSymbol()
{
    FormInit();

    CMM_ClearGridTableView(TvList);
    ClearSymbloList();

    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT SYMBLIB_NMBR,                        \r\n"
           "       IMAG_DATA,                           \r\n"
           "       SYMB_EXPL, SYMB_FILE_NM, SYMB_TYPE   \r\n"
           "  FROM TB_VMS_SYMB_LIB                      \r\n"
           " WHERE SYMBLIB_NMBR BETWEEN 8000 AND 8999   \r\n"
           "   AND DEL_YN = 'N'                         \r\n"
           " ORDER BY SYMBLIB_NMBR                      \r\n";

    int nRowHeight = 0;
    try
    {
        int nRow;
        TcxDataController *pGDC = TvList->DataController;
        TvList->BeginUpdate();
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLOpen(pADO);

            for( ; !pADO->Eof; pADO->Next())
            {
                nRow = pGDC->AppendRecord();
                pGDC->Values[nRow][ColLink1->Index] = pADO->FieldByName("SYMBLIB_NMBR")->AsString;
                pGDC->Values[nRow][ColLink2->Index] = pADO->FieldByName("IMAG_DATA")->AsVariant;
                pGDC->Values[nRow][ColLink3->Index] = pADO->FieldByName("SYMB_EXPL")->AsString;
                pGDC->Values[nRow][ColLink4->Index] = pADO->FieldByName("SYMB_TYPE")->AsString;

				Graphics::TBitmap *bitmap = new Graphics::TBitmap;
				bitmap->LoadFromStream(pADO->CreateBlobStream(pADO->FieldByName("IMAG_DATA"), bmRead));
				FListSymb->Add(bitmap);
                if (bitmap->Height+2 > nRowHeight) nRowHeight = bitmap->Height+3;
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("TVMSM420M::LoadImageSymbol", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("TVMSM420M::LoadImageSymbol", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        TvList->OptionsView->DataRowHeight = nRowHeight;
        TvList->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::LoadImageSymbolCell(String ANmbr)
{
    CMM_ClearGridTableView(TvImageCell);

    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT A.SYMBLIB_NMBR,                     \r\n"
           "       A.CELL_ID,                         \r\n"
           "       A.POSX, POSY,                      \r\n"
           "       A.VMS_IFSC_ID,                     \r\n"
           "       B.VMS_IFSC_NM,                     \r\n"
           "       B.DSPL_STRT_NODE_NM,               \r\n"
           "       B.DSPL_END_NODE_NM                 \r\n"
           "  FROM TB_VMS_SYMB_IFSC A,                \r\n"
           "       TB_VMS_IFSC      B                 \r\n"
           " WHERE A.SYMBLIB_NMBR  = :p01             \r\n"
           "   AND A.VMS_IFSC_ID   = B.VMS_IFSC_ID(+) \r\n"
           " ORDER BY CELL_ID                         \r\n";

    try
    {
        int nRow;
        TcxDataController *pGDC = TvImageCell->DataController;
        TvImageCell->BeginUpdate();
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", ANmbr);
            ITSDb_SQLOpen(pADO);

            for( ; !pADO->Eof; pADO->Next())
            {
                nRow = pGDC->AppendRecord();
                pGDC->Values[nRow][ColCellId->Index]   = pADO->FieldByName("CELL_ID")->AsString;
                pGDC->Values[nRow][ColCellPosX->Index] = pADO->FieldByName("POSX")->AsString;
                pGDC->Values[nRow][ColCellPosY->Index] = pADO->FieldByName("POSY")->AsString;
                pGDC->Values[nRow][ColIfscId->Index]   = pADO->FieldByName("VMS_IFSC_ID")->AsString;
                pGDC->Values[nRow][ColIfscNm->Index]   = pADO->FieldByName("VMS_IFSC_NM")->AsString;
                pGDC->Values[nRow][ColStrNm->Index]    = pADO->FieldByName("DSPL_STRT_NODE_NM")->AsString;
                pGDC->Values[nRow][ColEndNm->Index]    = pADO->FieldByName("DSPL_END_NODE_NM")->AsString;
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("TVMSM420M::LoadImageSymbolCell", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("TVMSM420M::LoadImageSymbolCell", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        TvImageCell->EndUpdate();
    }
}
//---------------------------------------------------------------------------

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

    DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::ColLink2CustomDrawCell(TcxCustomGridTableView *Sender,
          TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
#if 0
    int nRow = AViewInfo->GridRecord->RecordIndex;
    if (nRow < 0) return;

    if (nRow >= FListSymb->Count)
    {
        return;
    }
    try
    {
        Graphics::TBitmap *pBmp = (Graphics::TBitmap*)FListSymb->Items[nRow];

        TRect rc;
        TRect rcOrg = AViewInfo->Bounds;
        int nH = ( (rcOrg.Bottom - rcOrg.Top) - pBmp->Height ) / 2;

        rc.Top    = rcOrg.Top    + nH+1;
        rc.Bottom = rcOrg.Bottom - nH+1;
        rc.Left   = rcOrg.Left + 1;
        rc.Right  = rc.Left + pBmp->Width;

        ACanvas->Canvas->StretchDraw(rc, pBmp);
        ADone = true;
    }
    catch(Exception &e)
    {
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::BtnCellDeleteClick(TObject *Sender)
{
    TcxGridDataController *pGDC = TvImageCell->DataController;
    int nSelIdx = pGDC->FocusedRecordIndex;
    if (nSelIdx < 0) return;

	pGDC->BeginUpdate();
	pGDC->DeleteRecord(nSelIdx);
    pGDC->EndUpdate();

    UpdateCellColor();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::BtnCellApplyClick(TObject *Sender)
{
    TcxGridDataController *pGDC = TvImageCell->DataController;

    String sCellId;
    String sPosX;
    String sPosY;

    int nCellId = SeCellId->Value;
    int nPosX   = SePosX->Value;
    int nPosY   = SePosY->Value;
    int nMaxCellId = 0;

    bool bFound = false;
    sCellId = String(nCellId);
    sPosX   = String(nPosX);
    sPosY   = String(nPosY);

    int nFocusedIndex = 0;
    try
    {
        int nRows = pGDC->RecordCount;
        TvImageCell->BeginUpdate();
        pGDC->BeginUpdate();
        for (int ii = 0; ii < nRows; ii++)
        {
            String sTmpId = pGDC->Values[ii][ColCellId->Index];
            if (sTmpId == sCellId)
            {
                nFocusedIndex = ii;
                bFound = true;
            }
        }
        if (!bFound)
        {
            nFocusedIndex = pGDC->AppendRecord();
            //SeCellId->Value = nRows+1;
            pGDC->Values[nFocusedIndex][ColCellId->Index] = String(nRows+1);
        }
        pGDC->Values[nFocusedIndex][ColCellPosX->Index] = sPosX;
        pGDC->Values[nFocusedIndex][ColCellPosY->Index] = sPosY;
    }
    __finally
    {
        pGDC->EndUpdate();
        TvImageCell->EndUpdate();
        //if (pGDC->RecordCount > 0) pGDC->FocusedRecordIndex = nFocusedIndex;
        //SeCellId->Value = pGDC->RecordCount+1;
    }
    UpdateCellColor();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::ImgPreViewMouseDown(TObject *Sender, TMouseButton Button,
          TShiftState Shift, int X, int Y)
{
    try {
        SePosX->Value = X;
        SePosY->Value = Y;

        UpdateCellColor();

        TColor FOldColor = ImgPreView->Picture->Bitmap->Canvas->Pixels[SePosX->Value][SePosY->Value];

        ImgPreView->Picture->Bitmap->Canvas->Brush->Color = clWhite;
        ImgPreView->Picture->Bitmap->Canvas->FloodFill(SePosX->Value, SePosY->Value, FOldColor, fsSurface);

        BtnCellApplyClick(NULL);
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::ColAreaCustomDrawCell(TcxCustomGridTableView *Sender,
          TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    int nIdx = AViewInfo->GridRecord->RecordIndex;
    if (nIdx < 0)
        return;

    try
    {
        //String sCellId = VarToStr(TvImageCell->DataController->Values[nIdx][ColCellId->Index]);
        //nIdx = sCellId.ToIntDef(0);
        ACanvas->Brush->Color = clFuchsia;//APP_GetDisplayColor(nIdx);
        ACanvas->Font->Color = ACanvas->Brush->Color;
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::TvImageCellFocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
    TcxGridDataController *pGDC = TvImageCell->DataController;
    int nSelIdx = pGDC->FocusedRecordIndex;
    if (nSelIdx < 0) return;

    String sCellId = VarToStr(pGDC->Values[nSelIdx][ColCellId->Index]);
    String sPosX   = VarToStr(pGDC->Values[nSelIdx][ColCellPosX->Index]);
    String sPosY   = VarToStr(pGDC->Values[nSelIdx][ColCellPosY->Index]);

    SeCellId->Value = sCellId.ToIntDef(0);
    SePosX->Value = sPosX.ToIntDef(0);
    SePosY->Value = sPosY.ToIntDef(0);

#if 0
    try {
        TColor FOldColor = ImgPreView->Picture->Bitmap->Canvas->Pixels[SePosX->Value][SePosY->Value];
        if (FOldColor == clYellow) return;

        ImgPreView->Picture->Bitmap->Canvas->Brush->Color = clYellow;
        ImgPreView->Picture->Bitmap->Canvas->FloodFill(SePosX->Value, SePosY->Value, FOldColor, fsSurface);
    } catch(...) {}
#endif
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::UpdateCellColor()
{
    ImgPreView->Picture->Bitmap->FreeImage();
    ImgPreView->Picture->Bitmap = NULL;
    ImgPreView->Picture->Bitmap->Assign(ImgTemp->Picture->Bitmap);
    ImgPreView->Width  = ImgPreView->Picture->Bitmap->Width;
    ImgPreView->Height = ImgPreView->Picture->Bitmap->Height;

    TcxGridDataController *pGDC = TvImageCell->DataController;
    int nRows = pGDC->RecordCount;
    try
    {
        TvImageCell->BeginUpdate();
        pGDC->BeginUpdate();
        for (int ii = 0; ii < nRows; ii++)
        {
            String sCellId = VarToStr(pGDC->Values[ii][ColCellId->Index]);
            String sPosX   = VarToStr(pGDC->Values[ii][ColCellPosX->Index]);
            String sPosY   = VarToStr(pGDC->Values[ii][ColCellPosY->Index]);

            int X = sPosX.ToIntDef(0);
            int Y = sPosY.ToIntDef(0);

            TColor fillColor = clFuchsia;
            TColor FOldColor = ImgPreView->Picture->Bitmap->Canvas->Pixels[X][Y];
            //if (fillColor == FOldColor)
            //{
            //    fillColor = clWhite;
            //}
            //int nIdx = sCellId.ToIntDef(0);
            //ImgPreView->Picture->Bitmap->Canvas->Brush->Color = APP_GetDisplayColor(nIdx);
            ImgPreView->Picture->Bitmap->Canvas->Brush->Color = fillColor;
            ImgPreView->Picture->Bitmap->Canvas->FloodFill(X, Y, FOldColor, fsSurface);
        }
    }
    __finally
    {
        pGDC->EndUpdate();
        TvImageCell->EndUpdate();
    }

}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::SeCellIdPropertiesChange(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 TVMSM420M::TvListFocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
    if (!AFocusedRecord) return;
    DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM420M::PnlMenuDblClick(TObject *Sender)
{
    FIsUpdate = true;
}
//---------------------------------------------------------------------------

