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

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

#include "VMSM400MF.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"

TVMSM400M *VMSM400M = NULL;
//---------------------------------------------------------------------------

__fastcall TVMSM400M::TVMSM400M(TComponent* Owner)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    PnlVmsList->Visible = false;
    cxSplitter2->Visible = false;
    PnlSymbol->Align = alClient;

    CMM_LoadForm(g_sFormsDir, this);

    FUpdate= false;
    FTitle = Caption;//"VMS 심볼이미지 관리";

    //FRAMEVmsList1->Column02->Visible = false;
    FRAMEVmsList1->PnlTop->Visible = true;
    FRAMEVmsList1->PnlBottom->Visible = false;
    FRAMEVmsList1->ColumnSel->Visible = true;

    m_pGDC = FRAMEVmsList1->TvList->DataController;

	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;

    TNotifyEvent evt = CbType->Properties->OnChange;
    CbType->Properties->OnChange = NULL;
    CbType->Properties->Items->Clear();
    CbType->Properties->Items->Add(" 일반 이미지");
    CbType->Properties->Items->Add(" 대기환경등급 이미지");
    CbType->ItemIndex = 0;
    CbType->Properties->OnChange = evt;

    //BtnSaveImgFile->Caption = "Save as image file";
    //BtnSaveImgFile->Hint = "Save as image file";
}
//---------------------------------------------------------------------------

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

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

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

void __fastcall TVMSM400M::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;

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

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

    FRAMEVmsList1->UpdateList();

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

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

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

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

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

void __fastcall TVMSM400M::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]);

    if (EdVmsCd->Text == "SBT0") CbType->ItemIndex = 0;
    else
    if (EdVmsCd->Text == "SBT4") CbType->ItemIndex = 1;

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

void __fastcall TVMSM400M::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 TVMSM400M::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;
    }

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

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

bool __fastcall TVMSM400M::UpdateVmsImage(String ANmbr, String AExpl, String ATypeCd)
{
    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"
           "       SYMB_TYPE = :p04,                                  \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);
            ITSDb_SQLBind(pADO, "p04", ATypeCd);
			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 Symbol Update", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("VMS Symbol 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 TVMSM400M::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("TVMSM400M::InsertVmsImage", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("TVMSM400M::InsertVmsImage", 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 TVMSM400M::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;
	}

    bool bResult = false;
    String sSymbType = "SBT0";
    switch(CbType->ItemIndex)
    {
    case  1: sSymbType = "SBT4"; break;
    default: sSymbType = "SBT0"; break;
    }

    String sNmbr = EdNmbr->Text;
    String sExpl = EdExpl->Text.Trim();
    if (!FNewDb)
    {
        bResult = UpdateVmsImage(sNmbr, sExpl, sSymbType);
    }
    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, "", sSymbType);
    }

    if (bResult)
    {
        Application->MessageBox(lblText1->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_VmsImageSymbolUpdate();   // VMS서버로 이미지가 업데이트 되었음을 알린다.

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

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

    int nNmbr;

    if (!FrmLang->GetNextVmsImgeId(nNmbr, 6000, 6999))
    {
        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 TVMSM400M::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, false))
    {
        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();

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

void __fastcall TVMSM400M::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 TVMSM400M::EdImageFileNameClick(TObject *Sender)
{
    OpenBmp->Title    = FTitle;
    OpenBmp->FileName = "";
    OpenBmp->Execute();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM400M::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 = FrmLang->lblImage10->Caption;//"VMS 이미지 선택";
    sFName = sFName.UpperCase();
	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 TVMSM400M::ClearSymbloList()
{
	for(int ii = 0; ii < FListSymb->Count; ii++)
	{
		Graphics::TBitmap *bitmap = (Graphics::TBitmap *)FListSymb->Items[ii];
		delete bitmap;
	}
	FListSymb->Clear();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM400M::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 6000 AND 6999   \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("VMS Symbol Query", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("VMS Symbol Query", 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 TVMSM400M::TvListCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift,
          bool &AHandled)
{
	if (!ACellViewInfo) return;

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

void __fastcall TVMSM400M::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 TVMSM400M::BtnDownloadClick(TObject *Sender)
{
	if (EdNmbr->Text.IsEmpty())
	{
        Application->MessageBox(lblText2->Caption.c_str(),//L"VMS 이미지 제어기 다운로드\r\n이미지를 선택 하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    int nSelects = CMM_GetCheckCount(FRAMEVmsList1->TvList, FRAMEVmsList1->ColumnSel->Index);
    if (0 == nSelects)
    {
        Application->MessageBox(lblText3->Caption.c_str(),//L"VMS 이미지 제어기 다운로드\r\n다운로드할 VMS 제어기를 선택 하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        return;
    }

    String sNmbr = EdNmbr->Text;

    String sMsg;
    sMsg = FrmLang->lblImage7->Caption + ": " + sNmbr;//"VMS이미지번호: " + sNmbr;
    sMsg+= "\r\n" + lblText4->Caption;//"선택하신 VMS 이미지 정보를 선택한 VMS 제어기로 다운로드 하시겠습니까?";

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

    String sUserId = g_pLOGIN->sUserId;
    String sRgstDt = Now().FormatString("yyyymmddhhnnss");

    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "INSERT INTO TB_VMS_DOWNLOAD ( \r\n"
           "           RGST_DT,           \r\n"
           "           VMS_CTLR_NMBR,     \r\n"
           "           FILETYPE,          \r\n"
           "           FILEID,            \r\n"
           "           USER_ID)           \r\n"
           "  VALUES (                    \r\n"
           "           :p01,              \r\n"
           "           :p02,              \r\n"
           "           :p03,              \r\n"
           "           :p04,              \r\n"
           "           :p05 )             \r\n";

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

            ITSDb_SQLText(pADO, sQry);

            ITSDb_GetConnection()->BeginTrans();

            int nRowCnt = FRAMEVmsList1->TvList->ViewData->RecordCount;
            for (int ii = 0; ii < nRowCnt; ii++)
            {
                TcxCustomGridRow* ARow = FRAMEVmsList1->TvList->ViewData->Rows[ii];
                if (((bool)ARow->Values[FRAMEVmsList1->ColumnSel->Index]))
                {
                    String sVmsNmbr = VarToStr(ARow->Values[FRAMEVmsList1->Column01->Index]);

                    ITSDb_SQLBind(pADO, "p01", sRgstDt);
                    ITSDb_SQLBind(pADO, "p02", sVmsNmbr);
                    ITSDb_SQLBind(pADO, "p03", "1");
                    ITSDb_SQLBind(pADO, "p04", sNmbr);
                    ITSDb_SQLBind(pADO, "p05", sUserId);

                    ITSDb_SQLExec(pADO);
                }
            }

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

#if 0
    sMsg = "VMS 이미지 제어기 다운로드\r\n"
           "VMS 이미지를 제어기로 다운로드 요청하였습니다.\r\n"
           "VMS 제어기 통신상태에 따라 다운로드가 원활하게 진행되지 않을 수 있습니다.";
#else
    sMsg = lblText5->Caption;
#endif

    Application->MessageBox(sMsg.c_str(), FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

    //FRAMEVmsList1->BtnAllSelectClick((TObject*)FRAMEVmsList1->BtnAllClear);
}
//---------------------------------------------------------------------------

void __fastcall TVMSM400M::TvListFocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
    if (!AFocusedRecord) return;
    DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM400M::CbTypePropertiesChange(TObject *Sender)
{
    if (CbType->ItemIndex == 0)
    {
        if (LblDesc->Visible) LblDesc->Visible = false;
    }
    else
    {
        if (LblDesc->Visible == false) LblDesc->Visible = true;
    }
}
//---------------------------------------------------------------------------

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

