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

#pragma hdrstop

#include "CDSImageF.h"
#include "CDSCtlrF.h"
#include "VmsUtilsF.h"
#include "VMSCommLibF.h"

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

#pragma package(smart_init)

//---------------------------------------------------------------------------
TCDSImageCell::TCDSImageCell()
{
    IsDup = false;
}
//---------------------------------------------------------------------------

TCDSImageCell::~TCDSImageCell()
{
}
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
TCDSImage::TCDSImage()
{
    IMAG_DATA = NULL;
    IMAG_DATA = new TImage(NULL);
    UPDT_DT   = "-";
}
//---------------------------------------------------------------------------

TCDSImage::~TCDSImage()
{
    Clear();
    SAFE_DELETE(IMAG_DATA);
    FLists.RemoveAll();
}
//---------------------------------------------------------------------------
void TCDSImage::Clear()
{
    if (IMAG_DATA)
    {
        IMAG_DATA->Picture->Bitmap->FreeImage();
        IMAG_DATA->Picture->Assign(NULL);
    }
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------
TCDSImageManager *CDSImageManager = NULL;
//---------------------------------------------------------------------------

TCDSImageManager::TCDSImageManager()
{
}
//---------------------------------------------------------------------------
TCDSImageManager::~TCDSImageManager()
{
    FLists.RemoveAll();
}
//---------------------------------------------------------------------------
int TCDSImageManager::LoadVmsSymbolInfo(TADOConnection *ADbConn)
{
    String     sQry;
    TADOQuery *pADO = NULL;
    TStream   *pStream = NULL;
    int        nSelCnt = 0;
    int        ii;

    DDBSTART;

    //SYMB_TYPE: 심벌 유형(SBT0:일반심벌이미지,SBT1:소통정보배경,SBT2:소통정보이미지,SBT3:동영상,SBT4:대기환경등급)

    sQry = "SELECT A.*                    \r\n"
           "  FROM TB_VMS_SYMB_LIB A      \r\n"
           " WHERE A.DEL_YN = 'N'         \r\n";

    try
    {
        TCDSImage *pVmsImg;
        try
        {
            pADO = new TADOQuery(NULL);
            pADO->Connection = ADbConn;

			SQLText(pADO, sQry, true);

			SQLOpen(pADO);
            for( ; !pADO->Eof; pADO->Next())
            {
                AnsiString SYMB_LIB_NMBR = pADO->FieldByName("SYMBLIB_NMBR")->AsString;
                AnsiString UPDT_DT       = pADO->FieldByName("UPDT_DT")->AsString.Trim();
                AnsiString SYMB_TYPE     = pADO->FieldByName("SYMB_TYPE")->AsString.Trim(); //심벌 유형(SBT0:일반심벌이미지,SBT1:소통정보배경,SBT2:소통정보이미지,SBT3:동영상,SBT4:대기환경등급)
                AnsiString sSymbolNmbr   = SYMB_LIB_NMBR + "0";                             //소통정보이미지 때문에 이미지번호에 "0" 을 추가하여 이미지번호로 사용함

				pVmsImg = FLists.Find(sSymbolNmbr);
                if (!pVmsImg)
                {
                    pVmsImg = new TCDSImage();
                    pVmsImg->SYMB_LIB_NMBR = sSymbolNmbr;
                    FLists.Push(pVmsImg->SYMB_LIB_NMBR, pVmsImg);
                }

                if (SYMB_TYPE == "SBT4")    // 대기환경등급 이미지
                {
                    TStringList *sl = new TStringList;
                    try
                    {
                        sl->Delimiter = '^';
                        sl->StrictDelimiter = true;
                        sl->DelimitedText   = pADO->FieldByName("SYMB_EXPL")->AsString.Trim();

                        for (ii = 0; ii < sl->Count; ii++)
                        {
                            if (ii < MAX_GRADE_SYNB)
                            {
                                pVmsImg->GRAD_SYMB_LIB_NMBR[ii] = sl->Strings[ii].Trim() + "0";
                            }
                        }

                        if (sl) delete sl;
                        sl = NULL;
                    }
                    catch(Exception &e)
                    {
                    }
                }
                nSelCnt++;

                AnsiString LocalFileName = "";
                AnsiString SYMB_FILE_NM  = "";
                if (SYMB_TYPE == "SBT3")
                {
                    //동영상
                    SYMB_FILE_NM = pADO->FieldByName("SYMB_FILE_NM")->AsString.Trim();
                }
                else
                {
                    SYMB_FILE_NM = pVmsImg->SYMB_LIB_NMBR;
                    switch(pVmsImg->Type)
                    {
                    case vms_image_type_bmp: SYMB_FILE_NM += ".bmp"; break;
                    case vms_image_type_gif: SYMB_FILE_NM += ".gif"; break;
                    case vms_image_type_jpg: SYMB_FILE_NM += ".jpg"; break;
                    default: break;
                    }
                }
                LocalFileName = g_sFtpImageDir + SYMB_FILE_NM;

                if (FileExists(LocalFileName) && pVmsImg->UPDT_DT == UPDT_DT)
                {
                    //심볼 파일이 로컬 경로에 존재하지 않거나
                    //심볼 업데이트 시각이 다른 경우에만
                    //심볼울 로컬 디렉토리에 저장한다.
                    continue;
                }

                pVmsImg->Type         = vms_image_type_bmp;
                pVmsImg->UPDT_DT      = UPDT_DT;
                pVmsImg->SYMB_TYPE    = SYMB_TYPE;
                pVmsImg->SYMB_FILE_NM = SYMB_FILE_NM;                                       //동영상인 경우 동영상 파일명
                pVmsImg->IMAG_SIZE    = pADO->FieldByName("IMAG_SIZE")->AsInteger;          //	N	NUMBER(10)	    Y	0		이미지 사이즈
                pVmsImg->PLAY_TM      = pADO->FieldByName("PLAY_TM")->AsInteger;            //	N	NUMBER(10)	    Y	0		동영상 플레이 시간
                pVmsImg->LocalFileName = "";     // 이미지저장명 초기화
                pVmsImg->FtpFileName   = "";     // Ftp 다운로드 명을 초기화


                pVmsImg->Clear();
                pVmsImg->FLists.RemoveAll();

                TStream *pStream = NULL;
                try
                {
                    try
                    {
                        pStream = pADO->CreateBlobStream(pADO->FieldByName("IMAG_DATA"), bmRead);
                        if (pStream && pStream->Size > 0)
                        {
                            pStream->Position = 0;
                            bool bRes = true;
                            switch(pVmsImg->Type)
                            {
                            case vms_image_type_bmp: bRes = AssignBmp(pVmsImg->IMAG_DATA, pStream); break;
                            case vms_image_type_gif: bRes = AssignGif(pVmsImg->IMAG_DATA, pStream); break;
                            case vms_image_type_jpg: bRes = AssignJpg(pVmsImg->IMAG_DATA, pStream); break;
                            default: break;
                            }

                            pVmsImg->SYMB_FILE_NM = pVmsImg->SYMB_LIB_NMBR;

                            switch(pVmsImg->Type)
                            {
                            case vms_image_type_bmp: pVmsImg->SYMB_FILE_NM += ".bmp"; break;
                            case vms_image_type_gif: pVmsImg->SYMB_FILE_NM += ".gif"; break;
                            case vms_image_type_jpg: pVmsImg->SYMB_FILE_NM += ".jpg"; break;
                            default: break;
                            }

                            pVmsImg->LocalFileName = g_sFtpImageDir + pVmsImg->SYMB_FILE_NM;
                            pVmsImg->FtpFileName   = AnsiString(FTP_IMAGE) + "\\" + pVmsImg->SYMB_FILE_NM;
                            AnsiString BackupFileName = pVmsImg->LocalFileName+".bak";
                            if (FileExists(pVmsImg->LocalFileName))
                            {
                                try {
                                    DeleteFile(pVmsImg->LocalFileName);
                                    //MoveFile(pVmsImg->LocalFileName.c_str(), BackupFileName.c_str());
                                } catch(Exception &) {}
                            }

                            switch(pVmsImg->Type)
                            {
                            case vms_image_type_bmp: bRes = SaveToFileBmp(pVmsImg->IMAG_DATA, pVmsImg->LocalFileName); break;
                            case vms_image_type_gif: bRes = SaveToFileGif(pVmsImg->IMAG_DATA, pVmsImg->LocalFileName); break;
                            case vms_image_type_jpg: bRes = SaveToFileJpg(pVmsImg->IMAG_DATA, pVmsImg->LocalFileName); break;
                            default: break;
                            }

                            if (!bRes)
                            {
                                //if (FileExists(BackupFileName))
                                //{
                                //    MoveFile(BackupFileName.c_str(), pVmsImg->LocalFileName.c_str());
                                //}
                                pVmsImg->LocalFileName = "";
                                pVmsImg->FtpFileName   = "";
                            }
                        }
                    }
                    catch(Exception &e)
                    {
                        pVmsImg->LocalFileName = "";
                        pVmsImg->FtpFileName   = "";
                    }
                }
                __finally
                {
                    SAFE_DELETE(pStream);
                }

                if (pVmsImg->SYMB_TYPE == "SBT3")    //심벌 유형(SBT0:일반심벌이미지,SBT1:소통정보배경,SBT2:소통정보이미지,SBT3:동영상)
                {
                    //위에서 이미지저장하기 위해 파일명을 변경하기 때문에 여기서 동영상 파일명을 다시 읽어온다
                    pVmsImg->SYMB_FILE_NM  = pADO->FieldByName("SYMB_FILE_NM")->AsString.Trim(); //동영상인 경우 동영상 파일명
                    pVmsImg->LocalFileName = g_sFtpVideoDir + pVmsImg->SYMB_FILE_NM;
                    pVmsImg->FtpFileName   = AnsiString(FTP_VIDEO) + "\\" + pVmsImg->SYMB_FILE_NM; // Ftp 다운로드 명을 설정
#if 0
                    if (FileExists(pVmsImg->LocalFileName))
                    {
                        try {
                        //    DeleteFile(pVmsImg->LocalFileName);
                        } catch(Exception &) {}
                    }
                    else
                    {
                        TMemoryStream *Stream1 = (TMemoryStream *)pADO->CreateBlobStream(pADO->FieldByName("AVI_DATA"), bmRead);
                        try
                        {
                            try {
                                Stream1->SaveToFile(pVmsImg->LocalFileName);
                            } catch(Exception &) {
                                pVmsImg->FtpFileName = "";
                            }
                        }
                        __finally
                        {
                            SAFE_DELETE(pStream);
                        }
                    }
#endif
                }
                else
                if (pVmsImg->SYMB_TYPE == "SBT2")    //심벌 유형(SBT0:일반심벌이미지,SBT1:소통정보배경,SBT2:소통정보이미지,SBT3:동영상)
                {
                    //소통정보 등급에 따른 이미지를 새롭게 추가한다.
                    for (int nTrf = 1; nTrf <= 3; nTrf++)
                    {
                        sSymbolNmbr = SYMB_LIB_NMBR + AnsiString(nTrf);

                        //좌표가 바뀌더라도 셀정보에서 업데이트 한다. 이미지내용이 바뀌는 경우는 없다
                        //여기서는 일단 메모리에만 이미지정보를 생성한후 셀좌표에 따른 색깔을  LoadVmsSymbolCellInfo 함수에서 입힌후
                        //마지막에 파일로 저장한다.
                        TCDSImage* pTmpImg = FLists.Find(sSymbolNmbr);
                        if (pTmpImg) continue;  // 있으면 처리하지 않음

                        pTmpImg = new TCDSImage();
                        pTmpImg->SYMB_LIB_NMBR = sSymbolNmbr;
                        FLists.Push(pTmpImg->SYMB_LIB_NMBR, pTmpImg);

                        pTmpImg->Type         = pVmsImg->Type;
                        //pTmpImg->UPDT_DT      = pVmsImg->UPDT_DT;     //여기는 셀정보를 업데이트할때 사용하기 위해 설정하지 않는다
                        pTmpImg->SYMB_TYPE    = pVmsImg->SYMB_TYPE;
                        pTmpImg->SYMB_FILE_NM = pVmsImg->SYMB_FILE_NM; //동영상인 경우 동영상 파일명
                        pTmpImg->IMAG_SIZE    = pVmsImg->IMAG_SIZE;    //	N	NUMBER(10)	    Y	0		이미지 사이즈
                        pTmpImg->PLAY_TM      = pVmsImg->PLAY_TM;      //	N	NUMBER(10)	    Y	0		동영상 플레이 시간
                        pTmpImg->LocalFileName = "";     // 이미지저장명 초기화
                        pTmpImg->FtpFileName   = "";     // Ftp 다운로드 명을 초기화

                        pTmpImg->Clear();
                        pTmpImg->FLists.RemoveAll();

                        TStream *pTrfStream = NULL;
                        try
                        {
                            try
                            {
                                pTrfStream = pADO->CreateBlobStream(pADO->FieldByName("IMAG_DATA"), bmRead);
                                if (pTrfStream && pTrfStream->Size > 0)
                                {
                                    pTrfStream->Position = 0;
                                    switch(pTmpImg->Type)
                                    {
                                    case vms_image_type_bmp: AssignBmp(pTmpImg->IMAG_DATA, pTrfStream); break;
                                    case vms_image_type_gif: AssignGif(pTmpImg->IMAG_DATA, pTrfStream); break;
                                    case vms_image_type_jpg: AssignJpg(pTmpImg->IMAG_DATA, pTrfStream); break;
                                    default: break;
                                    }

                                    pTmpImg->SYMB_FILE_NM = pTmpImg->SYMB_LIB_NMBR;
                                    switch(pTmpImg->Type)
                                    {
                                    case vms_image_type_bmp: pTmpImg->SYMB_FILE_NM += ".bmp"; break;
                                    case vms_image_type_gif: pTmpImg->SYMB_FILE_NM += ".gif"; break;
                                    case vms_image_type_jpg: pTmpImg->SYMB_FILE_NM += ".jpg"; break;
                                    default: break;
                                    }

                                    pTmpImg->LocalFileName = g_sFtpImageDir + pTmpImg->SYMB_FILE_NM;
                                    pTmpImg->FtpFileName   = AnsiString(FTP_IMAGE) + "\\" + pTmpImg->SYMB_FILE_NM;
                                }
                            }
                            catch(Exception &e)
                            {
                                pTmpImg->LocalFileName = "";
                                pTmpImg->FtpFileName   = "";
                            }
                        }
                        __finally
                        {
                            SAFE_DELETE(pTrfStream);
                        }
                    }
                }
            }
        }
        catch(EDatabaseError &E)
        {
            DBERROR(String(E.ClassName()), E.Message, sQry);
            return -1;
        }
        catch(Exception &e)
        {
            DBERROR(String(e.ClassName()), e.Message, sQry);
            return -1;
        }
    }
    __finally
    {
        SQLFree(pADO);
    }

    if (LoadVmsSymbolCellInfo(ADbConn) < 0)
    {
        return -1;
    }

#if 0
    //FTP로 다운로드 해야 하기 때문에 파일로 저장해야 한다.
    //소통정보 이미지 같은 경우 디비에는 하나만 등록하고 읽어서 처리할때 소통등급별 이미지를 만들어서
    //소통등급별로 이미지를 만든다.
    //모든 이미지는 최초 한번만 로컬에 파일로 저장하도록 하고 소통정보 이미지인 경우에만 셀정보가 바뀔수 있기 때문에
    //새롭게 저장하도록 하자
    FOR_STL(TCDSImage*, pVmsImg, FLists)
    {
        MINFO("DCOM IMAGE: %s, %s, %s", pVmsImg->SYMB_LIB_NMBR.c_str(), pVmsImg->LocalFileName.c_str(), pVmsImg->FtpFileName.c_str());

        if (pVmsImg->SYMB_TYPE != "SBT2") continue; // 소통정보 이미지가 아닌경우 이미 위에서 저장 했음

        if (pVmsImg->SYMB_LIB_NMBR.ToIntDef(0) % 10)    // <== 요거는 원본 이미지가 아닌경우, 마지막심벌자리가 0(원본), 1(원활), 2(지체), 3(정체) 로 저장됨
        {
            //소통정보 원본 이미지는 이미 저장했으니까 소통등급에 따른 이미지만 여기서 저장
            bool bFail = false;
            try
            {
                //기존에 있으면 삭제한다.
                AnsiString BackupFileName = pVmsImg->LocalFileName+".bak";
                if (FileExists(pVmsImg->LocalFileName))
                {
                    try {
                        //DeleteFile(pVmsImg->LocalFileName);
                        MoveFile(pVmsImg->LocalFileName.c_str(), BackupFileName.c_str());
                    } catch(Exception &) {}
                }

                bool bRes = true;
                switch(pVmsImg->Type)
                {
                case vms_image_type_bmp: bRes = SaveToFileBmp(pVmsImg->IMAG_DATA, pVmsImg->LocalFileName); break;
                case vms_image_type_gif: bRes = SaveToFileGif(pVmsImg->IMAG_DATA, pVmsImg->LocalFileName); break;
                case vms_image_type_jpg: bRes = SaveToFileJpg(pVmsImg->IMAG_DATA, pVmsImg->LocalFileName); break;
                default: break;
                }

                if (!bRes)
                {
                    if (FileExists(BackupFileName))
                    {
                        MoveFile(BackupFileName.c_str(), pVmsImg->LocalFileName.c_str());
                    }
                }
            }
            catch(Exception &e)
            {
                pVmsImg->LocalFileName = "";
                pVmsImg->FtpFileName   = "";
                bFail = true;
            }

            if (bFail)
            {
                if (FileExists(pVmsImg->LocalFileName))
                {
                    try {
                        DeleteFile(pVmsImg->LocalFileName);
                    } catch(Exception &) {}
                }
            }
        }
    }
#endif

    CtlrItr it;
    for(it=CDSCtlrManager->FLists.FObjects.begin(); it != CDSCtlrManager->FLists.FObjects.end(); ++it)
    {
        TCDSCtlr *pObj = (TCDSCtlr*)it->second;

        pObj->FSymbolDownload = true;
    }

    IDBSTOP(nSelCnt);
    return nSelCnt;
}
//---------------------------------------------------------------------------
int TCDSImageManager::LoadVmsSymbolCellInfo(TADOConnection *ADbConn)
{
    String     sQry;
    TADOQuery *pADO = NULL;
    int        nSelCnt = 0;

    DDBSTART;

    sQry = "SELECT B.*, A.UPDT_DT                     \r\n"
           "  FROM TB_VMS_SYMB_LIB  A,                \r\n"
           "       TB_VMS_SYMB_IFSC B                 \r\n"
           " WHERE A.SYMBLIB_NMBR = B.SYMBLIB_NMBR    \r\n"
           " ORDER BY B.SYMBLIB_NMBR, B.CELL_ID       \r\n";

    try
    {
        TCDSImage     *pVmsImg;
        TCDSImageCell *pImgCell;
        try
        {
            pADO = new TADOQuery(NULL);
            pADO->Connection = ADbConn;

			SQLText(pADO, sQry, true);

			SQLOpen(pADO);
            for( ; !pADO->Eof; pADO->Next())
            {
                AnsiString UPDT_DT       = pADO->FieldByName("UPDT_DT")->AsString.Trim();
                AnsiString SYMB_LIB_NMBR = pADO->FieldByName("SYMBLIB_NMBR")->AsString.Trim();
                AnsiString sSymbolNmbr   = SYMB_LIB_NMBR + "0";   //소통정보이미지 때문에 이미지번호에 "0" 을 추가하여 이미지번호로 사용함

				pVmsImg = CDSImageManager->FLists.Find(sSymbolNmbr);
                if (!pVmsImg)
                {
                    continue;
                }

                pImgCell = new TCDSImageCell();

                pImgCell->SYMB_LIB_NMBR = sSymbolNmbr;
                pImgCell->CELL_ID       = pADO->FieldByName("CELL_ID")->AsInteger;
                pImgCell->POSX          = pADO->FieldByName("POSX")->AsInteger;
                pImgCell->POSY          = pADO->FieldByName("POSY")->AsInteger;
                pImgCell->VMS_IFSC_ID   = pADO->FieldByName("VMS_IFSC_ID")->AsString;
                pImgCell->IsDup         = false;

                FOR_STL(TCDSImageCell*, pDup, pVmsImg->FLists)
                {
                    if (pDup->VMS_IFSC_ID == pImgCell->VMS_IFSC_ID)
                    {
                        pImgCell->IsDup = true;
                        break;
                    }
                }
                pVmsImg->FLists.Push(pImgCell->CELL_ID, pImgCell);

                //소통정보 이미지인 경우(원활,지체,정체 이미지 생성)
                if (pVmsImg->SYMB_TYPE == "SBT2") //심벌 유형(SBT0:일반심벌이미지,SBT1:소통정보배경,SBT2:소통정보이미지,SBT3:동영상,SBT4:대기환경등급)
                {
                    for (int nTrf = 1; nTrf <= 3; nTrf++)
                    {
                        sSymbolNmbr = SYMB_LIB_NMBR + AnsiString(nTrf);

                        TCDSImage *pTmpImg = CDSImageManager->FLists.Find(sSymbolNmbr);
                        if (!pTmpImg) continue;

                        if (FileExists(pTmpImg->LocalFileName) && pTmpImg->UPDT_DT == UPDT_DT)
                        {
                            //변경된게 없으므로 저장하지 않는다.
                            continue;
                        }

                        pTmpImg->IMAG_DATA->Picture->Bitmap->Canvas->Lock();
                        try
                        {
                            pTmpImg->IMAG_DATA->Picture->Bitmap->Canvas->Brush->Color = GradeToFillColor(nTrf);
                            TColor clColor = pTmpImg->IMAG_DATA->Picture->Bitmap->Canvas->Pixels[pImgCell->POSX][pImgCell->POSY];
                            if (clColor == clWhite)
                            {
                                pTmpImg->IMAG_DATA->Picture->Bitmap->Canvas->Brush->Color = clWhite;
                            }
                            pTmpImg->IMAG_DATA->Picture->Bitmap->Canvas->FloodFill(pImgCell->POSX, pImgCell->POSY, clColor, fsSurface);
                        }
                        __finally
                        {
                            pTmpImg->IMAG_DATA->Picture->Bitmap->Canvas->Unlock();
                        }

                        //소통정보 소통등급 이미지를 로컬에 저장한다.
                        bool bRes = true;
                        AnsiString BackupFileName = pTmpImg->LocalFileName+".bak";
                        if (FileExists(pTmpImg->LocalFileName))
                        {
                            try {
                                DeleteFile(pTmpImg->LocalFileName);
                                //MoveFile(pTmpImg->LocalFileName.c_str(), BackupFileName.c_str());
                            } catch(Exception &) {}
                        }

                        switch(pTmpImg->Type)
                        {
                        case vms_image_type_bmp: bRes = SaveToFileBmp(pTmpImg->IMAG_DATA, pTmpImg->LocalFileName); break;
                        case vms_image_type_gif: bRes = SaveToFileGif(pTmpImg->IMAG_DATA, pTmpImg->LocalFileName); break;
                        case vms_image_type_jpg: bRes = SaveToFileJpg(pTmpImg->IMAG_DATA, pTmpImg->LocalFileName); break;
                        default: break;
                        }

                        if (bRes)
                        {
                            pTmpImg->UPDT_DT = UPDT_DT;
                        }
                        else
                        {
                            if (FileExists(BackupFileName))
                            {
                                MoveFile(BackupFileName.c_str(), pTmpImg->LocalFileName.c_str());
                            }
                            pTmpImg->LocalFileName = "";
                            pTmpImg->FtpFileName   = "";
                        }
                    }
                }
                pVmsImg->UPDT_DT = UPDT_DT;

                nSelCnt++;
            }
        }
        catch(EDatabaseError &E)
        {
            DBERROR(String(E.ClassName()), E.Message, sQry);
            return -1;
        }
        catch(Exception &e)
        {
            DBERROR(String(e.ClassName()), e.Message, sQry);
            return -1;
        }
    }
    __finally
    {
        SQLFree(pADO);
    }

    IDBSTOP(nSelCnt);
    return nSelCnt;
}
//---------------------------------------------------------------------------

