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

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

#include "FrmVmsMsgF.h"

#define LICENSE_KEY "FSXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "FFBaseComponent"
#pragma link "FFBasePlay"
#pragma link "FFPlay"
#pragma resource "*.dfm"
TFrmVmsMsg *FrmVmsMsg = NULL;
//---------------------------------------------------------------------------
__fastcall TFrmVmsMsg::TFrmVmsMsg(TComponent* Owner, TVmsCtlr *AObj)
    : TForm(Owner)
{
    FVmsObj = AObj;

    FQryHour = -1;
    FQryMin  = -1;

    for (int ii = 0; ii < MAX_VMSPHASE; ii++)
    {
        FVmsImage[ii] = new TImage(this);
        FVmsImage[ii]->Visible = false;
        FInterval[ii] = 1;
    }
    FPhaseCnt = 0;

    pADO->Connection = ITSDb_GetConnection();
    String sAVILibDir = g_sAppDir + "LibAV";

    FFPlayer1->SetLicenseKey(LICENSE_KEY);
    FFPlayer1->DisableFPUExceptions();
    if (!FFPlayer1->LoadAVLib(sAVILibDir))
    {
#if 0
        if (g_AppCfg.sLang != "kr") Application->MessageBox(L"Stream display library load failed.", L"Stream display fail", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        else                        Application->MessageBox(L"영상표출 라이브러리를 로드하지 못하였습니다.", L"영상표출 오류", MB_OK|MB_ICONERROR|MB_APPLMODAL);
#endif
    }

    SetVmsForm();
}
//---------------------------------------------------------------------------

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

void __fastcall TFrmVmsMsg::FormShow(TObject *Sender)
{
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    if (FVmsObj)
    {
        Caption = FVmsObj->VMS_CTLR_ID + ": " + FVmsObj->VMS_NM;
    }
    TmrDisp->Interval = 100;
    TmrDisp->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::SetVmsForm()
{
    if (!FVmsObj) return;

    int nW = PnlVmsMsgDisp->Width;
    int nH = PnlVmsMsgDisp->Height;

    String sType1 = "VMM";
#if 0
    if (FVmsObj->VMS_MODL_TYPE_CD == "VMM0")
        sType1 = "문자식";
    else
    if (FVmsObj->VMS_MODL_TYPE_CD == "VMM1")
#endif
        sType1 = "도형식";


    nH = FVmsObj->HEIGHT;
    nW = FVmsObj->WIDTH;

    ClientWidth = nW;
    ClientHeight= nH + PnlOffer->Height;

    PnlVmsMsgDisp->Width  = nW;
    PnlVmsMsgDisp->Height = nH;

    ImgForm->Width  = nW;
    ImgForm->Height = nH;
    ImgForm->Picture->Bitmap->Width = nW;
    ImgForm->Picture->Bitmap->Height= nH;

    PnlVmsMsgDisp->ParentColor = false;
    PnlVmsMsgDisp->Color = clBlack;
    ImgForm->Left = 0;
    ImgForm->Top  = 0;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::ClearVmsForm()
{
    TCanvas *pCanvas = ImgForm->Canvas;
    try {
        pCanvas->Lock();
        try {
            pCanvas->Pen->Color = clWhite;
            pCanvas->Pen->Width = 0;
            pCanvas->Pen->Style = psClear;
            pCanvas->Brush->Style = bsSolid;
            pCanvas->Brush->Color = clBlack;
            pCanvas->Rectangle(0, 0, ImgForm->Width, ImgForm->Height);
        } catch(...) { }
    } __finally {
        ImgForm->Refresh();
        pCanvas->Unlock();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::TmrDispTimer(TObject *Sender)
{
#if 1
    PnlOffer->Caption = " 제공시각:";
    PnlOffer->Font->Color = clBlack;

    int nDispTime = 1000;
    TCanvas *pCanvas = ImgForm->Canvas;
    FPhaseCnt = FVmsObj->VmsMsg->Total;
    try
    {
        TmrDisp->Enabled = false;

        FVmsObj->Lock();
        pCanvas->Lock();

        try {
            if (FVmsObj->VmsMsg->Total == 0)
            {
                Caption = FVmsObj->VMS_CTLR_ID + ": " + FVmsObj->VMS_NM + " [0/0]";
                ImgForm->Visible = false;
                FDispIndex = -1;
                return;
            }
            if (ImgForm->Visible == false) ImgForm->Visible = true;

            if (FDispIndex >= FVmsObj->VmsMsg->Total || FDispIndex >= INT_VMS_MAX_FORM)
            {
                FDispIndex = 0;
            }

            //Caption = FVmsObj->VMS_CTLR_ID + ": " + FVmsObj->VMS_NM + " [" + String(FDispIndex+1) + "/" + String(FPhaseCnt) + "]";

#if 1
            //nDispTime = FVmsObj->VMS_PHSE_CHNG_CYCL;
            if (nDispTime < 3) nDispTime = 3;
            if (nDispTime > 9) nDispTime = 10;
            nDispTime = nDispTime * 1000;
#else
            nDispTime = FVmsObj->VmsMsg->PHASE[FDispIndex].DSPL_HH * 1000;
#endif

            Graphics::TBitmap *pBitmap = FVmsObj->VmsMsg->PHASE[FDispIndex].pVmsBmp;
            if (pBitmap)
            {
                SetStretchBltMode(ImgForm->Canvas->Handle, MAXSTRETCHBLTMODE);//HALFTONE);//MAXSTRETCHBLTMODE)//STRETCH_HALFTONE;
                ImgForm->Canvas->CopyRect(Classes::Rect(0, 0, ImgForm->Width, ImgForm->Height),
                                          pBitmap->Canvas,
                                          Classes::Rect(0, 0, pBitmap->Width, pBitmap->Height));
            }
        } catch(...) {}

        PnlOffer->Caption = " 제공시각: " + ITSUtil_FormatStr(FVmsObj->VmsMsg->OFFER_DT, STR_DATETIME) + " [" + String(FDispIndex+1) + "/" + String(FPhaseCnt) + "]";
        if (FVmsObj->VmsMsg->OFFER_YN)
            PnlOffer->Font->Color = clBlack;
        else
            PnlOffer->Font->Color = clRed;

    }
    __finally
    {
        FVmsObj->UnLock();

        ImgForm->Refresh();
        pCanvas->Unlock();

        FDispIndex++;

        TmrDisp->Interval = nDispTime;
        TmrDisp->Enabled  = true;
    }

#else
    TmrDisp->Enabled = false;

    bool bQry = false;
    if (FQryMin < 0)
    {
        bQry = true;
        FQryMin = StrToInt(Now().FormatString("nn"));
        if ((FQryMin % 5) == 0)
            FQryMin--;
    }
    else
    {
        int nCurMin = StrToInt(Now().FormatString("nn"));
        int nCurSec = StrToInt(Now().FormatString("ss"));
        if ((nCurMin % 5) == 0 && nCurSec >= 45)
        {
            if (FQryMin != nCurMin)
            {
                FQryMin = nCurMin;
                bQry = true;
            }
        }
    }

    if (bQry)
    {
        SelectVmsForm();
        if (FPhaseCnt == 0)
        {
            PnlVmsMsgDisp->ParentColor = false;
            PnlVmsMsgDisp->Color = clBlack;
            ImgForm->Visible = false;
        }
        else
        {
            ImgForm->Visible = true;
        }
    }
    else
    {
        if (FDispIndex >= FPhaseCnt)
        {
            FDispIndex = 0;
        }
    }

    int nInterval = 5;   //5초
    try
    {
        if (FDispIndex < FPhaseCnt)
        {
            nInterval = FInterval[FDispIndex];
            try {
                ClearVmsForm();
                ImgForm->Picture->Assign(FVmsImage[FDispIndex]->Picture);
                Caption = FVmsObj->VMS_CTLR_ID + ": " + FVmsObj->VMS_NM + " [" + String(FDispIndex+1) + "/" + String(FPhaseCnt) + "]";
            } catch(...) {}

            FDispIndex++;
        }
    }
    catch(...)
    {
    }
    TmrDisp->Interval = nInterval * 1000;
    TmrDisp->Enabled = true;
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::SelectVmsForm()
{
    bool bImage = false;
    String sQry;

    FDispIndex= 0;
    FPhaseCnt = 0;

    if (!FVmsObj)
    {
        return;
    }

#if 0
    sQry = "SELECT VMS_CTLR_NMBR, DSPL_DT,                                \r\n"
           "       VMS_DSPL_MSG_IMAG, NVL(DSPL_HH, 2) AS DSPL_HH          \r\n"
           "  FROM TB_VMS_DSPL_PRST                                       \r\n"
           " WHERE VMS_CTLR_NMBR = :p01                                   \r\n"
           "   AND DSPL_DT >= TO_CHAR(SYSDATE-8/1440, 'YYYYMMDDHH24MISS') \r\n";

#else
    sQry = "SELECT A.VMS_CTLR_NMBR, A.PHASE, A.DSPL_HH, A.DNLD_YN,          \r\n"
           "       A.VMS_FORM_DSPL_MTHD_CD, A.TRFC_SITU_TYPE_CD, A.DSPL_DT, \r\n"
           "       TO_CHAR(SYSDATE - 8/1440, 'YYYYMMDDHH24MISS') AS SVC_DT, \r\n"
           "       A.VMS_DSPL_MSG_IMAG                                      \r\n"
           "  FROM TB_VMS_DSPL_PRST A,                                      \r\n"
           "       (SELECT VMS_CTLR_NMBR, MAX(DSPL_DT) AS DSPL_DT           \r\n"
           "          FROM TB_VMS_DSPL_PRST                                 \r\n"
           "         WHERE VMS_CTLR_NMBR = :p01                             \r\n"
           "         GROUP BY VMS_CTLR_NMBR) B                              \r\n"
           " WHERE A.VMS_CTLR_NMBR = B.VMS_CTLR_NMBR                        \r\n"
           "   AND A.DSPL_DT       = B.DSPL_DT                              \r\n"
           " ORDER BY A.VMS_CTLR_NMBR, A.PHASE                              \r\n";
#endif
    try
    {
        pADO->Connection = ITSDb_GetConnection();

        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FVmsObj->VMS_CTLR_NMBR);
        ITSDb_SQLOpen(pADO);

        for( ; !pADO->Eof; pADO->Next())
        {
            if (FPhaseCnt >= MAX_VMSPHASE) break;

            FInterval[FPhaseCnt] =  pADO->FieldByName("DSPL_HH")->AsInteger;
            if (FInterval[FPhaseCnt] < 1 || FInterval[FPhaseCnt] > 5)
            {
                FInterval[FPhaseCnt] = 3;
            }

            TStream *pStream = NULL;
            pStream = pADO->CreateBlobStream(pADO->FieldByName("VMS_DSPL_MSG_IMAG"), bmRead);

            TImage *pImage = FVmsImage[FPhaseCnt];
            try
            {
                try {
                    pImage->Canvas->Lock();
                    pStream->Position = 0;
                    pImage->Picture->Bitmap->LoadFromStream(pStream);

                    FPhaseCnt++;
                } catch(...) {}
            }__finally{
                pImage->Canvas->Unlock();
                SAFE_DELETE(pStream);
            }
        }
        ITSDb_SQLClose(pADO);
    }
    catch(EDatabaseError &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(...)
    {
        throw Exception("알수없는 오류가 발생하였습니다.");
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::FormDestroy(TObject *Sender)
{
    TmrDisp->Enabled = false;
    try {
        for (int ii = 0; ii < MAX_VMSPHASE; ii++)
        {
            if (FVmsImage[ii]) delete FVmsImage[ii];
        }
        if (FVmsObj) FVmsObj->FData1 = NULL;
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::FFPlayer1State(TObject *Sender, TPlayState APlayState)
{
    switch(APlayState)
    {
    case Ffbasecomponent::psPlay:
    case Ffbasecomponent::psResume:
        break;
    case Ffbasecomponent::psPause:
    case Ffbasecomponent::psStep:
        break;
    case Ffbasecomponent::psStop:
    case Ffbasecomponent::psEnd:
        if (FFPlayer1->ScreenHandle != NULL)
        {
            FFPlayer1->Stop(true);
            PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
            UpdateWindow(FFPlayer1->ScreenHandle);
            FFPlayer1->ScreenHandle = NULL;
            TmrDisp->Interval = 100;
            TmrDisp->Enabled = true;
            if (ImgForm->Visible == false) {
                ImgForm->Visible = true;
            }
        }
        break;
    }
}
//---------------------------------------------------------------------------

