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

#include <vcl.h>
#pragma hdrstop

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

#include "VMSFORM0F.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "dxSkinBlack"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinsCore"
#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 "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 "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "cxLabel"
#pragma link "FFBaseComponent"
#pragma link "FFBasePlay"
#pragma link "FFPlay"
#pragma link "FRAME_VmsStatusF"
#pragma resource "*.dfm"

#define     WIDTH_GAP   3
#define     HEIGHT_GAP  3

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

//TVMSFORM0 *VMSFORM0 = NULL;

//---------------------------------------------------------------------------
__fastcall TVMSFORM0::TVMSFORM0(TComponent* Owner, TVmsCtlr *AVmsObj)
    : TForm(Owner)
{
#if 0
    if (g_AppCfg.sLang != "kr")
    {
        lblText1->Caption = "Provide time:";
        lblText2->Caption = "Controller Ping";
        lblText3->Caption = "Web camera Ping";
    }
#endif

    FVmsObj = AVmsObj;

    FScrollBox   = NULL;

    FSelected    = false;
    FDisplayMode = 0;
    FZoomRate    = 1.0;
    FDispIndex   = 0;
    FPlay        = false;

    FWndParent = NULL;
    FZoomView  = false;

    PnlForm->ParentColor = false;
    PnlForm->Color       = clBtnFace;

    FDispW = FVmsObj->WIDTH;
    FDispH = FVmsObj->HEIGHT;
    //PnlName->Caption = "[" + FVmsObj->VMS_CTLR_ID + "] " + FVmsObj->VMS_NM;
    PnlName->Caption = FVmsObj->VMS_NM;
    PnlName->Hint = (FVmsObj->VMS_CTLR_NMBR) + " [" + FVmsObj->VMS_CTLR_ID + "] \r\n" + FVmsObj->VMS_NM;

    FGapW = 16;
    FGapH =  8;

    PnlForm->Align = alCustom;
    PnlForm->Anchors = TAnchors() >> akLeft >> akTop >> akRight >> akBottom;
    //PnlForm->Locked = true;

#if 0
    ImgCommError->Parent = ImgCommNormal->Parent;
    ImgCommError->Left = ImgCommNormal->Left;
    ImgCommError->Top  = ImgCommNormal->Top;
    ImgCommError->Visible = false;
    ImgCommNormal->Visible= true;
#else
    ImgState1->Parent = ImgState0->Parent;
    ImgState2->Parent = ImgState0->Parent;
    ImgState1->Left = ImgState0->Left;
    ImgState1->Top  = ImgState0->Top;
    ImgState2->Left = ImgState0->Left;
    ImgState2->Top  = ImgState0->Top;

    ImgState1->Visible = false;
    ImgState2->Visible = false;
#endif

    LoadLocalSkin();

    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 TVMSFORM0::LoadLocalSkin()
{
    PnlMain->ParentColor = false;
    PnlMain->Color       = clBtnFace;

    PnlForm->ParentColor = false;
    PnlForm->Color       = clBlack;

    FRAME_VmsStatus1->LoadLocalSkin();
#if 0
    PnlDoor->ParentColor = false;
    PnlFan->ParentColor = false;
    PnlHeater->ParentColor = false;
    PnlModule->ParentColor = false;
    PnlPower->ParentColor = false;
    PnlTemp->ParentColor = false;
    PnlOprMode->ParentColor = false;
#endif
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::FormDestroy(TObject *Sender)
{
    TmrDisp->Enabled = false;
}
//---------------------------------------------------------------------------

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

void __fastcall TVMSFORM0::SetFormSize(int AFormW/* = 0 */, float AZoomRate/* = 1.0*/)
{
//384*64, 2단12열 기준으로
//표출되는 화면은 넓이 370으로 설정, 1920 에서 최대 5개 VMS 표출되게...
int DispW = 370;
int MaxW  = VmsCtlrManager->FMaxWidth >= 384 ? 384 : VmsCtlrManager->FMaxWidth;
    if (FVmsObj->WIDTH > MaxW)
    {
        FZoomRate = ((float)DispW / (float)FVmsObj->WIDTH);
    }
    else
    {
        FZoomRate = ((float)DispW / (float)MaxW);
    }
    FDispW = FVmsObj->WIDTH  * FZoomRate;
    FDispH = FVmsObj->HEIGHT * FZoomRate;

    if (FDispW > FVmsObj->WIDTH)
    {
        // 배율이 1.0 이상 넘어가면 원본을 보여주자... 확대해서 보여줄 필요 없음.
        //FDispW = FVmsObj->WIDTH;
        //FDispH = FVmsObj->HEIGHT;
    }
    int nFormW = DispW + (3+3);
    int nFormH = FDispH + (3+3) + PnlTitle->Height + PnlBottom->Height;

    try
    {
        LockWindowUpdate(Handle);

        Width  = nFormW;
        Height = nFormH;

        PnlForm->Width  = FDispW + (2+2);
        PnlForm->Height = FDispH + (2+2);
        PnlForm->Left = (PnFormBack->Width - PnlForm->Width) / 2;
        PnlForm->Top  = (PnFormBack->Height - PnlForm->Height) / 2;
        PnlForm->Visible = true;

        ImgForm->Width = FDispW;
        ImgForm->Height= FDispH;
        ImgForm->Picture->Bitmap->Width  = ImgForm->Width;
        ImgForm->Picture->Bitmap->Height = ImgForm->Height;
        APP_ImageClear(ImgForm->Canvas, 0, 0, ImgForm->Width, ImgForm->Height, clBlack);
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::SelectForm(bool ASelect)
{
    FSelected = ASelect;
    if (ASelect)
    {
        PopupMenu = PopupMenu1;
        PnlMain->ParentColor = false;
        PnlMain->Color       = clBtnHighlight;//clBackground;
        this->ParentColor = false;
        this->Color = clRed;
    }
    else
    {
        PopupMenu = NULL;
        PnlMain->ParentColor = false;
        PnlMain->Color       = clBtnFace;
        this->ParentColor = true;
    }
#if 0
    if (FVmsObj)
    {
        if (FVmsObj->STATE.Comm != vms_comm_normal)
        {
            if (ASelect)
            {
                PnlMain->ParentColor = false;
                PnlMain->Color       = clMaroon;//clBackground;
                this->ParentColor = false;
                this->Color = clRed;
            }
            else
            {
                PnlMain->ParentColor = false;
                PnlMain->Color       = clPurple;//clBackground;
                this->ParentColor = false;
                this->Color = clRed;
            }
        }
    }
#else
    if (FVmsObj)
    {
        if (FVmsObj->STATE.Comm != vms_comm_normal)
        {
            PnlForm->Caption = "통신 Offline";
            if (ImgForm->Visible)
            {
                if (g_AppCfg.isDispOfflineMsg == false)
                {
                    //통신오프라인시 메시지 표출을 하지 않을 경우
                    ImgForm->Visible = false;
                }
            }
        }
        else
        {
            PnlForm->Caption = "표출정보가 없습니다.";
            if (ImgForm->Visible == false)
            {
                ImgForm->Visible = true;
            }
        }
    }
#endif
}
//---------------------------------------------------------------------------

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

    PopupMenu = NULL;
    if (!FVmsObj)
    {
        PnlName->Caption = "VMS";
        ImgForm->Visible = false;
    }
    RefreshVmsStatus();
    TmrDisp->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::SetPlay(bool APlay)
{
    FPlay = APlay;
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::TmrDispTimer(TObject *Sender)
{
    int nDispTime = 1000;
    TCanvas *pCanvas = ImgForm->Canvas;
    try
    {
        TmrDisp->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;
        }

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

        try {
            if (FVmsObj->VmsMsg->Total == 0)
            {
                if (FVmsObj->VmsMsg->IsLoading)
                {
                    return;
                }
                PnlSeq->Caption = "0/0";
                ImgForm->Visible = false;
                FDispIndex = -1;
                PnlSvcTime->Caption = "" + FrmLang->lblText1->Caption + " -";//제공시각: -";
                return;
            }

            if (FVmsObj->STATE.Comm == vms_comm_normal)
            {
                //통신이 온라인인데 메시지표출화면이 숨겨져 있으면 보이게 한다.
                if (ImgForm->Visible == false) ImgForm->Visible = true;
            }
            else
            {
                //통신이 오프라인일때
                if (g_AppCfg.isDispOfflineMsg)
                {
                    //메시지 표출하는 경우
                    if (ImgForm->Visible == false) ImgForm->Visible = true;
                }
                else
                {
                    //메시지 표출하지 않는 경우
                    if (ImgForm->Visible == true) ImgForm->Visible = false;
                }
            }

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

            PnlSvcTime->Caption = "" + FrmLang->lblText1->Caption + " " + ITSUtil_FormatStr(FVmsObj->VmsMsg->OFFER_DT, STR_DATETIME);

#if 0
            //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;
            if (nDispTime > 5000) nDispTime = 5000;
#endif
            FCycle = FVmsObj->VmsMsg->PHASE[FDispIndex].DSPL_HH;
            if (FPlay == false)
            {
                return;
            }

            PnlSeq->Caption = String(FDispIndex+1) + "/" + String(FVmsObj->VmsMsg->Total);

            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));
            }

#if 0
            if (FVmsObj->VmsMsg->PHASE[FDispIndex].VMS_SCH_FORM_TYPE == eSchTp_video  ||
                FVmsObj->VmsMsg->PHASE[FDispIndex].VMS_SCH_FORM_TYPE == eSchTp_stream )
            {
                FFPlayer1->AspectRatio = -1;
                FFPlayer1->TryOpen(FVmsObj->VmsMsg->PHASE[FDispIndex].VMS_DSPL_MSG_TXT.Trim(), PnlForm->Handle);
                ImgForm->Visible = false;
            }
#endif
        } catch(...) {}
    }
    __finally
    {
        FVmsObj->UnLock();

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

        FDispIndex++;

        PnlSvcTime->Font->Color = FVmsObj->VmsMsg->OFFER_YN ? clNavy : clRed;

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

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

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

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

void __fastcall TVMSFORM0::OnFormClick(TObject *Sender)
{
    if (FScrollBox) FScrollBox->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::RefreshVmsMessage()
{
    TmrDisp->Enabled = false;
    FDispIndex = 0;
    TmrDisp->Interval= 300;
    TmrDisp->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::RefreshVmsStatus()
{
#if 0
    if (FVmsObj->STATE.Comm == vms_comm_normal)
    {
        if (!ImgCommNormal->Visible) ImgCommNormal->Visible = true;
        if ( ImgCommError->Visible)  ImgCommError->Visible  = false;
    }
    else
    {
        if (!ImgCommError->Visible) ImgCommError->Visible  = true;
        if (ImgCommNormal->Visible) ImgCommNormal->Visible = false;
    }
#else
    switch(FVmsObj->RunState)
    {
    case state_normal:
        if (!ImgState0->Visible) ImgState0->Visible = true;
        if ( ImgState1->Visible) ImgState1->Visible = false;
        if ( ImgState2->Visible) ImgState2->Visible = false;
        break;
    case state_module:
        if ( ImgState0->Visible) ImgState0->Visible = false; //false
        if ( ImgState1->Visible) ImgState1->Visible = false;
        if (!ImgState2->Visible) ImgState2->Visible = true;  //true
        break;
    default:
        if ( ImgState0->Visible) ImgState0->Visible = false;
        if (!ImgState1->Visible) ImgState1->Visible = true;
        if ( ImgState2->Visible) ImgState2->Visible = false;
        break;
    }
#endif

    FRAME_VmsStatus1->RefreshStatus(FVmsObj);
    SelectForm(FSelected);
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::PopupMenu1Popup(TObject *Sender)
{
    MnuVmsInfId->Caption = "[" + FVmsObj->VMS_CTLR_ID + "]";
    MnuCtlrPing->Caption = FrmLang->lblText2->Caption + " - " + FVmsObj->VMS_CTLR_IP;//"제어기 Ping - " +  FVmsObj->VMS_CTLR_IP;
    if (FVmsObj->WEB_CMRA_IP == "")
    {
        MnuWebcamPing->Caption = FrmLang->lblText3->Caption;//"웹카메라 Ping";
        MnuWebcamPing->Enabled = false;
    }
    else
    {
        MnuWebcamPing->Caption = FrmLang->lblText3->Caption + " - " + FVmsObj->WEB_CMRA_IP;//"웹카메라 Ping - " +  FVmsObj->WEB_CMRA_IP;
        MnuWebcamPing->Enabled = true;
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::MnuNetworkPingClick(TObject *Sender)
{
    String sIp = FVmsObj->VMS_CTLR_IP;

    TMenuItem *pMenu = (TMenuItem*)Sender;
    if (pMenu->Tag == 1)
    {
        sIp = FVmsObj->WEB_CMRA_IP;
    }

    ITSUtil_NetworkPing(sIp);
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::MnuClick(TObject *Sender)
{
    if (!FVmsObj) return;

#if 0
    TMenuItem *pMenu = (TMenuItem*)Sender;
    ST_WMMESSAGE *pWmMsg = new ST_WMMESSAGE;
    pWmMsg->hWnd  = (HWND)Handle;
    pWmMsg->pForm = (void*)this;
    pWmMsg->nMsg  = D_FORMCALL;
    pWmMsg->sSender   = "VMS0000M";     // 동적생성된 폼은 폼의 이름 +_1, +_2, ... 식으로 이름이 바뀐다.
    pWmMsg->sReceiver = String(pMenu->Tag);
    pWmMsg->sMsg      = FVmsObj->Id;
    PostMessage(Application->MainForm->Handle, WM_PLUGINFORM, (WPARAM)pWmMsg, 0);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::PnlNameClick(TObject *Sender)
{
    if (FScrollBox) FScrollBox->SetFocus();
    if (FWndParent)
    {
        POST_MSG(FWndParent, WM_VMS_SELECT, (WPARAM)FVmsObj, (LPARAM)this);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::PnlNameDblClick(TObject *Sender)
{
    if (FScrollBox) FScrollBox->SetFocus();
    if (FWndParent)
    {
        POST_MSG(FWndParent, WM_VMS_SELECT_DBLCLICK, (WPARAM)FVmsObj, (LPARAM)this);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSFORM0::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;
    }
}
//---------------------------------------------------------------------------

