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

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

#include "VMSM510MF.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 link "IdBaseComponent"
#pragma link "IdCoder"
#pragma link "IdCoder3to4"
#pragma link "IdCoderMIME"
#pragma resource "*.dfm"

TVMSM510M *VMSM510M = NULL;
//---------------------------------------------------------------------------

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

    FUpdate= false;
    FTitle = Caption;//"VMS 객체이미지 선택";

	FListSymb = new TList;

    EditMode = false;
    m_bSelected = false;

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

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

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

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

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

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

void __fastcall TVMSM510M::FormInit()
{
	EdNmbr->Text = "";

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

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

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

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

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

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

void __fastcall TVMSM510M::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    //
}
//---------------------------------------------------------------------------

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

    EdNmbr->Text  = VarToStr(pDc->Values[nRow][ColLink1->Index]);
}
//---------------------------------------------------------------------------

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

String __fastcall TVMSM510M::DecodeAndUnCompress(String input)
{
    return "";
}

String __fastcall TVMSM510M::BitmapToBase64String(Graphics::TBitmap *AImage)
{
    return "";
}
//---------------------------------------------------------------------------

Graphics::TBitmap * __fastcall TVMSM510M::Base64StringToBitmap(String AImageString)
{
    TIdDecoderMIME *Decodeur = new TIdDecoderMIME(NULL);
    TMemoryStream *TempMem = new TMemoryStream();
    Graphics::TBitmap *result = new Graphics::TBitmap();
    try {
        try {
            Decodeur->DecodeBegin(TempMem);
            Decodeur->Decode(AImageString);
            Decodeur->DecodeEnd();

            TempMem->Position = 0;
            result->LoadFromStream(TempMem);
        }
        catch(Exception &e) {
            result->Assign(ImgFail->Picture->Bitmap);
        }
    }
    __finally {
        if (Decodeur) delete Decodeur;
        if (TempMem) delete TempMem;
    }
    return result;
}
//---------------------------------------------------------------------------

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

    CMM_ClearGridTableView(TvList);
    ClearSymbloList();

    String vmsTypeCd = "SBT0";
    String apiUri = g_AppCfg.sRestApiUri + "/api/vms/manager/symb-sbt0";
    TMcJsonItem *ObjList = NULL;

    if (FImageType == 0)    //이미지 심볼
    {
        vmsTypeCd = "SBT0";
        apiUri = g_AppCfg.sRestApiUri + "/api/vms/manager/symb-sbt0";
    }
    else
    if (FImageType == 1)    //소통정보배경이미지
    {
        vmsTypeCd = "SBT1";
        apiUri = g_AppCfg.sRestApiUri + "/api/vms/manager/symb-sbt1";
    }
    else
    if (FImageType == 2)    //소통정보이미지
    {
        vmsTypeCd = "SBT2";
        apiUri = g_AppCfg.sRestApiUri + "/api/vms/manager/symb-sbt2";
    }
    else
    if (FImageType == 3)    //동영상
    {
        vmsTypeCd = "SBT3";
        apiUri = g_AppCfg.sRestApiUri + "/api/vms/manager/symb-sbt3";
    }
    else
    if (FImageType == 4)    //대기환경 이미지
    {
        vmsTypeCd = "SBT4";
        apiUri = g_AppCfg.sRestApiUri + "/api/vms/manager/symb-sbt4";
    }
    else return;

    int nRowHeight = 0;
    try
    {
        int nRow;
        TcxDataController *pGDC = TvList->DataController;
        TvList->BeginUpdate();
        try
        {
            ObjList = TRestObjectManager::RequestGet(apiUri);
            if (ObjList == NULL) {
                return;
            }

            for (int ii = 0; ii < ObjList->Count; ii++) {
                nRow = pGDC->AppendRecord();
                String imageString = TRestObjectManager::GetValue(ObjList->Items[ii], "imag_data");
                Graphics::TBitmap *bitmap = Base64StringToBitmap(imageString);
                TStream	*pImgStream = new TMemoryStream();
                try {
                    bitmap->SaveToStream(pImgStream);
                    void    *p;
                    Variant  v;
                    int aBound[]={0, pImgStream->Size - 1};
                    v = VarArrayCreate(aBound, 1, varByte);
                    p = VarArrayLock(v);
                    pImgStream->Position = 0;
                    pImgStream->Read(p, pImgStream->Size);
                    VarArrayUnlock(v);
                    pGDC->Values[nRow][ColLink2->Index] = v;
                } catch(Exception &e) {}
                SAFE_DELETE(pImgStream);

                pGDC->Values[nRow][ColLink1->Index] = TRestObjectManager::GetValue(ObjList->Items[ii], "symb_lib_nmbr");
                pGDC->Values[nRow][ColLink3->Index] = TRestObjectManager::GetValue(ObjList->Items[ii], "symb_expl");
                pGDC->Values[nRow][ColLink4->Index] = vmsTypeCd;

#if 1
                /* 이미지를 가지고 가는 곳에서 이것을 참조하기 때문에 주석으로 막지 말자.... */
				//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;
#endif
            }
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (ObjList) delete ObjList;
        //TvList->OptionsView->DataRowHeight = nRowHeight;
        TvList->EndUpdate();
    }
}
//---------------------------------------------------------------------------

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

    DisplayInfo();
    Sleep(200);
    BtnSelImageClick((TObject*)BtnSelImage);
}
//---------------------------------------------------------------------------

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

void __fastcall TVMSM510M::BtnSelImageClick(TObject *Sender)
{
    if (EdNmbr->Text == "")
    {
        Application->MessageBox(lblText1->Caption.c_str(),//L"VMS 객체이미지 선택\r\nVMS 객체이미지를 목록에서 선택하세요.",
                                FTitle.c_str(),
                                MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    m_bSelected = true;
    Close();
}
//---------------------------------------------------------------------------

