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

#pragma hdrstop

#include "CDSFormF.h"
#include "VmsUtilsF.h"
#include "VMSCommLibF.h"

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

#pragma package(smart_init)

//---------------------------------------------------------------------------
TCDSFormObj::TCDSFormObj()
{
    pImage  = NULL;
    pImage  = new TImage(NULL);
}
//---------------------------------------------------------------------------

TCDSFormObj::~TCDSFormObj()
{
    Clear();
    if (pImage)
    {
        delete pImage;
        pImage = NULL;
    }
}
//---------------------------------------------------------------------------
void TCDSFormObj::Clear()
{
    if (pImage)
    {
        pImage->Picture->Bitmap->FreeImage();
        pImage->Picture->Assign(NULL);
    }
}
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
TCDSForm::TCDSForm()
{
    TrfIfsc     = false;
    TrfAxis     = false;
    TrfFixed    = false;
    IsNewForm   = true;
    TrfBakImgId = "";
}
//---------------------------------------------------------------------------

TCDSForm::~TCDSForm()
{
    Clear();
    FLists.RemoveAll();
}
//---------------------------------------------------------------------------
void TCDSForm::Clear()
{
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------
TCDSFormManager *CDSFormManager = NULL;
//---------------------------------------------------------------------------

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

    DDBSTART;

    sQry = "SELECT A.VMS_FORM_ID,                           \r\n"
           "       A.VMS_TYPE_CD,                           \r\n"
           "       A.VMS_FORM_TYPE_CD,                      \r\n"
           "       A.VMS_FORM_COLR_CD,                      \r\n"
           "       A.VMS_FORM_DSPL_DRCT_CD,                 \r\n"
           "       A.VMS_FORM_DSPL_MTHD_CD,                 \r\n"
           "       A.SYMBLIB_NMBR,                          \r\n"
           "       TRIM(A.VMS_FORM_NM) AS VMS_FORM_NM,      \r\n"
           "       TRIM(A.VMS_FORM_EXPL) AS VMS_FORM_EXPL,  \r\n"
           "       A.UPDT_DT                                \r\n"
           "  FROM TB_VMS_FORM A                            \r\n";

    try
    {
        TCDSForm *pCDSForm;
        try
        {
            pADO = new TADOQuery(NULL);
            pADO->Connection = ADbConn;

			SQLText(pADO, sQry, true);

			SQLOpen(pADO);
            for( ; !pADO->Eof; pADO->Next())
            {
                AnsiString VMS_FORM_ID = pADO->FieldByName("VMS_FORM_ID")->AsString.Trim();
				pCDSForm = FLists.Find(VMS_FORM_ID);
                if (!pCDSForm)
                {
                    pCDSForm = new TCDSForm();
                    pCDSForm->VMS_FORM_ID = VMS_FORM_ID;
                    CDSFormManager->FLists.Push(pCDSForm->VMS_FORM_ID, pCDSForm);
                }
                pCDSForm->FLists.RemoveAll();

                pCDSForm->TrfBakImgId           = ""; //소통정보 배경 이미지 ID
                pCDSForm->VMS_TYPE_CD           = pADO->FieldByName("VMS_TYPE_CD")->AsString;
                pCDSForm->VMS_FORM_TYPE_CD      = pADO->FieldByName("VMS_FORM_TYPE_CD")->AsInteger;
                pCDSForm->VMS_FORM_COLR_CD      = pADO->FieldByName("VMS_FORM_COLR_CD")->AsInteger;
                pCDSForm->VMS_FORM_DSPL_DRCT_CD = pADO->FieldByName("VMS_FORM_DSPL_DRCT_CD")->AsInteger;
                pCDSForm->VMS_FORM_DSPL_MTHD_CD = pADO->FieldByName("VMS_FORM_DSPL_MTHD_CD")->AsInteger;
                pCDSForm->VMS_FORM_NM           = pADO->FieldByName("VMS_FORM_NM")->AsString;
                pCDSForm->VMS_FORM_EXPL         = pADO->FieldByName("VMS_FORM_EXPL")->AsString;
                pCDSForm->TrfIfsc               = false;
                pCDSForm->TrfAxis               = false;
                pCDSForm->TrfFixed              = false;

                AnsiString UPDT_DT = pADO->FieldByName("UPDT_DT")->AsString;

                // 정적폼(홍보) 같은 경우 최초 또는 변경되었을 때에만 사용할수 있도록(제어기로 한번만 다운로드 할수 있도록)
                // 체크 플래그를 두어 확인할수 있도록 한다.
                pCDSForm->IsNewForm = false;
                if (pCDSForm->VMS_FORM_TYPE_CD == eFormTp_hongbo && pCDSForm->UPDT_DT != UPDT_DT)
                {
                    pCDSForm->IsNewForm = true;
                }

#if 0
                if (pCDSForm->VMS_FORM_TYPE_CD == eFormTp_hongbo)
                {
                    //정적인 폼인 경우 폼의 이미지를 파일로 저장해 둔다
                    pCDSForm->LocalFileName = g_sFtpStaticDir + pCDSForm->VMS_FORM_ID + ".bmp";
                    pCDSForm->FtpFileName   = AnsiString(FTP_STATIC) + "\\" + pCDSForm->VMS_FORM_ID + ".bmp";

                    // 파일이 존재하지 않거나 업데이트 시각이 다르면 새로 홍보폼 이미지를 생성한다.
                    if (pCDSForm->UPDT_DT != UPDT_DT || !FileExists(pCDSForm->LocalFileName))
                    {
                        AnsiString BackupFileName = pCDSForm->LocalFileName+".bak";
                        if (FileExists(pCDSForm->LocalFileName))
                        {
                            try {
                                //DeleteFile(pCDSForm->LocalFileName);
                                MoveFile(pCDSForm->LocalFileName.c_str(), BackupFileName.c_str());
                            } catch(Exception &) {}
                        }
                        try
                        {
                            TMemoryStream *Stream1 = (TMemoryStream *)pADO->CreateBlobStream(pADO->FieldByName("VMS_FORM_IMAG"), bmRead);
                            Stream1->SaveToFile(pCDSForm->LocalFileName);
                            SAFE_DELETE(Stream1);
                        }
                        catch(Exception &e)
                        {
                            if (FileExists(BackupFileName))
                            {
                                MoveFile(BackupFileName.c_str(), pCDSForm->LocalFileName.c_str());
                            }
                            pCDSForm->LocalFileName = "";
                            pCDSForm->FtpFileName   = "";
                        }
                    }
                }
#endif
                pCDSForm->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);
    }

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

    IDBSTOP(nSelCnt);
    return nSelCnt;
}
//---------------------------------------------------------------------------
int TCDSFormManager::LoadVmsFormObjectInfo(TADOConnection *ADbConn)
{
    String     sQry;
    TADOQuery *pADO = NULL;
    TStream   *pStream = NULL;
    int        nSelCnt = 0;

    DDBSTART;

    sQry = "SELECT B.VMS_FORM_ID,                           \r\n"
           "       B.FORM_OBJECT_ID,                        \r\n"
           "       B.VMS_FORM_DSPL_ROW,                     \r\n"
           "       B.VMS_FORM_DSPL_CLMN,                    \r\n"
           "       B.VMS_FORM_OBJECT_TYPE_CD,               \r\n"
           "       B.VMS_FONT_NAME_CD,                      \r\n"
           "       B.VMS_FONT_COLR_CD,                      \r\n"
           "       B.VMS_FONT_BOLD,                         \r\n"
           "       B.VMS_FONT_SIZE,                         \r\n"
           "       B.VMS_FONT_ALIGN,                        \r\n"
           "       B.VMS_DSPL_TXT,                          \r\n"
           "       B.VMS_DSPL_XCRDN,                        \r\n"
           "       B.VMS_DSPL_YCRDN,                        \r\n"
           "       B.VMS_DSPL_WIDTH,                        \r\n"
           "       B.VMS_DSPL_HEIGHT,                       \r\n"
           "       B.VMS_DSPL_BLINKING,                     \r\n"
           "       B.VMS_DSPL_BKCOLOR,                      \r\n"
           "       B.VMS_DSPL_SIZE,                         \r\n"
           "       B.TRFC_FILL_CD,                          \r\n"
           "       B.SYMBLIB_NMBR,                          \r\n"
           "       B.VMS_IFSC_ID                            \r\n"
           "  FROM TB_VMS_FORM        A,                    \r\n"
           "       TB_VMS_FORM_OBJECT B,                    \r\n"
           "       TB_VMS_SYMB_LIB    C                     \r\n"
           " WHERE A.VMS_FORM_ID   = B.VMS_FORM_ID          \r\n"
           "   AND B.SYMBLIB_NMBR  = C.SYMBLIB_NMBR(+)      \r\n"
           " ORDER BY B.VMS_FORM_ID, B.FORM_OBJECT_ID       \r\n";

    int notFound = 0;

    try
    {
        TCDSForm    *pCDSForm;
        TCDSFormObj *pCDSFormObj;
        try
        {
            pADO = new TADOQuery(NULL);
            pADO->Connection = ADbConn;

			SQLText(pADO, sQry, true);

			SQLOpen(pADO);
            for( ; !pADO->Eof; pADO->Next())
            {
                AnsiString sFormId = pADO->FieldByName("VMS_FORM_ID")->AsString.Trim();
				pCDSForm = FLists.Find(sFormId);
                if (!pCDSForm)
                {
                   MDEBUG("DCOM Not Found Form Object by FormId: %d", sFormId.c_str());
                   continue;
                }
                nSelCnt++;

                pCDSFormObj = new TCDSFormObj();

                pCDSFormObj->VMS_FORM_OBJECT_ID      = pADO->FieldByName("FORM_OBJECT_ID")->AsInteger;
                pCDSFormObj->VMS_FORM_ID             = pADO->FieldByName("VMS_FORM_ID")->AsString;
                pCDSFormObj->VMS_FORM_DSPL_ROW       = pADO->FieldByName("VMS_FORM_DSPL_ROW")->AsInteger;
                pCDSFormObj->VMS_FORM_DSPL_CLMN      = pADO->FieldByName("VMS_FORM_DSPL_CLMN")->AsInteger;
                pCDSFormObj->VMS_FORM_OBJECT_TYPE_CD = pADO->FieldByName("VMS_FORM_OBJECT_TYPE_CD")->AsInteger;
                pCDSFormObj->VMS_FONT_NAME_CD        = pADO->FieldByName("VMS_FONT_NAME_CD")->AsInteger;
                pCDSFormObj->VMS_FONT_COLR_CD        = pADO->FieldByName("VMS_FONT_COLR_CD")->AsInteger;
                pCDSFormObj->VMS_FONT_BOLD           = pADO->FieldByName("VMS_FONT_BOLD")->AsInteger;
                pCDSFormObj->VMS_FONT_SIZE           = pADO->FieldByName("VMS_FONT_SIZE")->AsInteger;
                pCDSFormObj->VMS_FONT_ALIGN          = pADO->FieldByName("VMS_FONT_ALIGN")->AsInteger;
                pCDSFormObj->VMS_DSPL_TXT            = pADO->FieldByName("VMS_DSPL_TXT")->AsString;
                pCDSFormObj->VMS_DSPL_XCRDN          = pADO->FieldByName("VMS_DSPL_XCRDN")->AsInteger;
                pCDSFormObj->VMS_DSPL_YCRDN          = pADO->FieldByName("VMS_DSPL_YCRDN")->AsInteger;
                pCDSFormObj->VMS_DSPL_WIDTH          = pADO->FieldByName("VMS_DSPL_WIDTH")->AsInteger;
                pCDSFormObj->VMS_DSPL_HEIGHT         = pADO->FieldByName("VMS_DSPL_HEIGHT")->AsInteger;
                pCDSFormObj->VMS_DSPL_BLINKING       = pADO->FieldByName("VMS_DSPL_BLINKING")->AsInteger;
                pCDSFormObj->VMS_DSPL_BKCOLOR        = pADO->FieldByName("VMS_DSPL_BKCOLOR")->AsInteger;
                pCDSFormObj->VMS_DSPL_SIZE           = pADO->FieldByName("VMS_DSPL_SIZE")->AsInteger;
                pCDSFormObj->TRFC_FILL_CD            = pADO->FieldByName("TRFC_FILL_CD")->AsString;
                pCDSFormObj->SYMB_LIB_NMBR           = pADO->FieldByName("SYMBLIB_NMBR")->AsString;
                pCDSFormObj->VMS_IFSC_ID             = pADO->FieldByName("VMS_IFSC_ID")->AsString;

                pCDSForm->FLists.Push(pCDSFormObj->VMS_FORM_OBJECT_ID, pCDSFormObj);

                int nObjType = pCDSFormObj->VMS_FORM_OBJECT_TYPE_CD;

                if (pCDSForm->VMS_FORM_TYPE_CD == eFormtp_figure)
                {
                    //도형식 소통정보 폼인데 구간 소통정보를 하단에 표출하는 경우
                    //하나의 폼이 여러개의 소통정보를 표출되도록 하기 위함
                    switch(nObjType)
                    {
                    //////////////////////// 20200515 추가함(S)
                    case  0://,  ,  @문자열
                    case  1://,  ,  @심볼
                    case  2://,  ,  @이미지
                        if (pCDSFormObj->TRFC_FILL_CD == "F")
                        {
                            //하단고정일 경우 도형식하단에 표출할 소통정보가 없을 경우 표출하는 정보임
                            pCDSForm->TrfFixed = true;
                        }
                        break;
                    //////////////////////// 20200515 추가함(E)
                    case 11://, '	@구간명
                    case 12://, '	@시점명
                    case 13://, '	@종점명
                    case 14://, '	@소통상황
                    case 15://, '	@통행시간
                    case 16://, '	@통행속도
                    case 17://, '	@소통정보이미지
                    case 18://, '	@지점명
                        pCDSForm->TrfIfsc = true;
                        break;
                    case 93://, '	@축시점명(순환)
                    case 94://, '	@축종점명(순환)
                    case 95://, '	@축소통상황(순환)
                    case 96://, '	@축통행시간(순환)
                        pCDSForm->TrfAxis = true;
                        break;
                    }
                }

                if (nObjType == 3)
                {
                    pCDSForm->TrfBakImgId = pCDSFormObj->SYMB_LIB_NMBR + "0";
                }

                if (nObjType ==   1 || //심볼
                    nObjType ==   2 || //이미지(파일에서 직접입력한것임)
                    nObjType ==   3 || //소통정보배경이미지
                    nObjType ==  17 || //소통정보이미지1
                    nObjType ==  27 || //소통정보이미지2
                    nObjType ==  37 || //소통정보이미지3
                    nObjType ==  47 || //소통정보이미지4
                    nObjType == 200 || //동영상이미지
                    nObjType == 300 )  //스트리밍영상이미지
                {
                    pCDSFormObj->Clear();
                    //pCDSFormObj->pImage->Picture->Bitmap->PixelFormat = g_AppCfg.PixelFormat;//g_AppCfg.PixelFormat;//pf4bit;
                    //심볼에서 읽지 않고 폼오브젝트에 있는 이미지를 사용함
#if 1
                    try
                    {
                        TCDSImage *pVmsImg = CDSImageManager->FLists.Find(pCDSFormObj->SYMB_LIB_NMBR+"0");
                        if (pVmsImg && pVmsImg->IMAG_DATA)
                        {
                            pCDSFormObj->pImage->Picture->Bitmap->Assign(pVmsImg->IMAG_DATA->Picture->Bitmap);
                        }
                        else
                        {
                            if (pCDSFormObj->SYMB_LIB_NMBR == "")
                                notFound++;
                            else
                                MERROR("MAIN LoadVmsFormObjectInfo Symbol Not Found: %s", pCDSFormObj->SYMB_LIB_NMBR.c_str());
                        }
                    }
                    catch(Exception &e)
                    {
                         MERROR("MAIN LoadVmsFormObjectInfo Symbol Find Failed: %s, %s, %s", pCDSFormObj->SYMB_LIB_NMBR.c_str(), AnsiString(e.ClassName()).c_str(), AnsiString(e.Message).c_str());
                    }
#else

                    TStream *pStream = pADO->CreateBlobStream(pADO->FieldByName("IMAG_DATA"), bmRead);
                    try
                    {
                        if (pStream && pStream->Size > 0)
                        {
                            pStream->Position = 0;
                            AssignBmp(pCDSFormObj->pImage, pStream);
                        }
                    }
                    __finally
                    {
                        SAFE_DELETE(pStream);
                    }
#endif
                }
            }

            if (notFound > 0) {
                MERROR("MAIN LoadVmsFormObjectInfo Symbol Not Found: %d EA.", notFound);
            }
        }
        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 0
    if (0)//g_LogCfg.Debug)
    {
        FOR_STL(TCDSForm*, pTmp, FormManager->FLists)
        {
            MDEBUG("DCOM Vms Form: %s, Objects: %d", pTmp->VMS_FORM_ID.c_str(), pTmp->FLists.Size());
        }
    }
#endif

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

