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

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

#include "FrmVmsMsgF.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "FFBaseComponent"
#pragma link "FFBasePlay"
#pragma link "FFPlay"
#pragma resource "*.dfm"

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

TFrmVmsMsg *FrmVmsMsg;
//---------------------------------------------------------------------------
__fastcall TFrmVmsMsg::TFrmVmsMsg(TComponent* Owner, TVmsCtlr *AObj)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());

    FObj = AObj;

    FQryHour = -1;
    FQryMin  = -1;

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

    pADO->Connection = ITSDb_GetConnection();
    SetVmsForm();

    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
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::FormClose(TObject *Sender, TCloseAction &Action)
{
    TmrTicker->Enabled = false;
    TmrVmsMsgDisp->Enabled = false;
    if (FFPlayer1->ScreenHandle != NULL)
    {
        FFPlayer1->Stop(true);
        PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
        UpdateWindow(FFPlayer1->ScreenHandle);
        FFPlayer1->ScreenHandle = NULL;
    }

    Action = caFree;
}
//---------------------------------------------------------------------------

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

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

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

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

    nH = FObj->HEIGHT;
    nW = FObj->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::VmsFormReload()
{
    FFormQuery = true;
    TmrVmsMsgDisp->Interval = 500;
    TmrVmsMsgDisp->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsMsg::TmrVmsMsgDispTimer(TObject *Sender)
{
    TmrVmsMsgDisp->Enabled = false;

    TmrTicker->Enabled = false;
    LblTicker->Caption = " -  ";

    if (FFPlayer1->ScreenHandle != NULL)
    {
        FFPlayer1->Stop(true);
        PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
        UpdateWindow(FFPlayer1->ScreenHandle);
        FFPlayer1->ScreenHandle = NULL;
        ImgForm->Visible = true;
    }

    PnlOffer->Caption = " " + lblTm->Caption + ":";
    PnlOffer->Font->Color = clBlack;
    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 || FFormQuery)
    {
        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];
            FCycle = nInterval;
            try
            {
                ClearVmsForm();
                ImgForm->Picture->Assign(FVmsImage[FDispIndex]->Picture);
                //Caption = FObj->VMS_CTLR_ID + ": " + FObj->VMS_NM + " [" + String(FDispIndex+1) + "/" + String(FPhaseCnt) + "]";
            } catch(...) {}

            PnlOffer->Caption = " " + lblTm->Caption + ": " + ITSUtil_FormatStr(FOfferTime[FDispIndex], STR_DATETIME) + " [" + String(FDispIndex+1) + "/" + String(FPhaseCnt) + "]";
            if (FOffer[FDispIndex])
                PnlOffer->Font->Color = clBlack;
            else
                PnlOffer->Font->Color = clRed;

#if 0
            if (FVMS_SCH_FORM_TYPE[FDispIndex] == eSchTp_video  ||
                FVMS_SCH_FORM_TYPE[FDispIndex] == eSchTp_stream )
            {
                FFPlayer1->AspectRatio = -1;
                FFPlayer1->TryOpen(FVMS_DSPL_MSG_TXT[FDispIndex].Trim(), PnlForm->Handle);
                ImgForm->Visible = false;
            }
#endif
            FDispIndex++;
        }
    }
    catch(...)
    {
    }

    FFormQuery = false;

    LblTicker->Caption = " " + String(FCycle) + "  ";
    TmrTicker->Enabled  = true;

    TmrVmsMsgDisp->Interval = nInterval * 1000;
    TmrVmsMsgDisp->Enabled = true;
}
//---------------------------------------------------------------------------

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

    FDispIndex= 0;
    FPhaseCnt = 0;

    if (!FObj)
    {
        return;
    }

    sQry = "SELECT A.*,                                                     \r\n"
           "       TO_CHAR(SYSDATE - 8/1440, 'YYYYMMDDHH24MISS') AS SVC_DT  \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"
           "         GROUP BY VMS_CTLR_NMBR) B                              \r\n"
           " WHERE A.VMS_CTLR_NMBR = :p01                                   \r\n"
           "   AND 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";

    try
    {
        pADO->Connection = ITSDb_GetConnection();

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

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

            String DSPL_DT = pADO->FieldByName("DSPL_DT")->AsString;
            String SVC_DT  = pADO->FieldByName("SVC_DT")->AsString;
            String DNLD_YN = pADO->FieldByName("DNLD_YN")->AsString;
            if (DSPL_DT >= SVC_DT)
            {
                 FOffer[FPhaseCnt] = true;
            }
            else
            {
                 FOffer[FPhaseCnt] = false;
            }
            if (DNLD_YN == "N") FOffer[FPhaseCnt] = false;

            FOfferTime[FPhaseCnt] = DSPL_DT;

            FVMS_SCH_FORM_TYPE[FPhaseCnt] = pADO->FieldByName("VMS_SCH_FORM_TYPE")->AsInteger;

            FVMS_DSPL_MSG_TXT[FPhaseCnt] = "";
            if (FVMS_SCH_FORM_TYPE[FPhaseCnt] == eSchTp_video  ||
                FVMS_SCH_FORM_TYPE[FPhaseCnt] == eSchTp_stream )
            {
                FVMS_DSPL_MSG_TXT[FPhaseCnt] = pADO->FieldByName("VMS_DSPL_MSG_TXT")->AsString.Trim();
            }

            FInterval[FPhaseCnt] =  pADO->FieldByName("DSPL_HH")->AsInteger;
            if (FInterval[FPhaseCnt] <=  0) FInterval[FPhaseCnt] = 3;
            //if (FInterval[FPhaseCnt] >= 10) FInterval[FPhaseCnt] = 10;

            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();
                if (pStream) delete pStream;
            }
        }
        ITSDb_SQLClose(pADO);
    }
    catch(EDatabaseError &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(...)
    {
        throw Exception(FrmLang->lblDbErr->Caption);//"알수없는 오류가 발생하였습니다.");
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TFrmVmsMsg::TmrTickerTimer(TObject *Sender)
{
    TmrTicker->Enabled  = false;
    FCycle--;
    LblTicker->Caption = " " + String(FCycle) + "  ";
    if (FCycle > 0) TmrTicker->Enabled  = true;
}
//---------------------------------------------------------------------------

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:
        if (FFPlayer1->ScreenHandle != NULL)
        {
            PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
            UpdateWindow(FFPlayer1->ScreenHandle);
            FFPlayer1->ScreenHandle = NULL;
        }
        break;
    case Ffbasecomponent::psEnd:
        {
            FFPlayer1->Stop(true);
            PostMessage(FFPlayer1->ScreenHandle, CM_INVALIDATE, 0, 0);
            UpdateWindow(FFPlayer1->ScreenHandle);
            FFPlayer1->ScreenHandle = NULL;
        }
        break;
    }
}
//---------------------------------------------------------------------------

