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

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

#include "CTV0100MF.h"
#include "CTV0101MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxControls"
#pragma link "cxGraphics"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "dxSkinBlack"
#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 "dxSkinMcSkin"
#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 "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "cxRadioGroup"
#pragma link "cxButtons"
#pragma resource "*.dfm"
TCTV0100M *CTV0100M = NULL;

//---------------------------------------------------------------------------
__fastcall TCTV0100M::TCTV0100M(TComponent* Owner)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    LoadLocalSkin();

    //FMonitoringType = enMonitoringStopImage;

    if (FormStyle != fsMDIChild) CMM_LoadForm(g_sFormsDir, this);

	FListForm = new TList();

    FReady = false;

    FFormWidth  = 209;
    FFormHeight = 276;

    IsFormResizing = false;
    FOldWidth = PnlCenter->Width;
    FOldHeight= PnlCenter->Height;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::CommClose()
{
    try
    {
        ClearFormList();
        SAFE_DELETE(FListForm);

        if (FormStyle != fsMDIChild) CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::FormCreate(TObject *Sender)
{
    ScrollBox->ParentColor = true;
    LoadNoStopImage();
    InitMonitoringForm();
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::LoadNoStopImage()
{
    try
    {
        String sImgNoDataFile = ExtractFilePath(Application->ExeName) + "\\image\\NoStopImage.bmp";
        try {
            ImgNoData->Picture->LoadFromFile(sImgNoDataFile);
        } catch(...) {}
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::FormShow(TObject *Sender)
{
    Refresh();
    Application->ProcessMessages();

    ScrollBox->Align = alClient;
    FScrollWidth = ScrollBox->Width;

    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::FormActivate(TObject *Sender)
{
    ActivateForm(true);
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::FormDeactivate(TObject *Sender)
{
    ActivateForm(false);
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::LoadLocalSkin()
{
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    BtnSearchClick(NULL);
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::FormClose(TObject *Sender, TCloseAction &Action)
{
    try {
        CommClose();

        CTV0100M = NULL;
        Action = caFree;
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::OnMainFormMessage(TMessage &Msg)
{
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::OnVmsStateRefreshMessage(TMessage &Msg)
{
#if 0
    for(int ii = 0; ii < FListForm->Count; ii++)
    {
        TVMSBACKM *pForm = (TVMSBACKM*)FListForm->Items[ii];
        pForm->RefreshVmsStatus();
    }

    FRAMEVmsState1->SelVmsObj = FSelVmsObj;
#endif
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::OnVmsFormRefreshMessage(TMessage &Msg)
{
#if 0
    for(int ii = 0; ii < FListForm->Count; ii++)
    {
        TVMSBACKM *pForm = (TVMSBACKM*)FListForm->Items[ii];
        pForm->RefreshVmsMessage();
    }

    FRAMEVmsState1->SelVmsObj = FSelVmsObj;

    if (FSelVmsObj)
    {
        FRAMEVmsMsgList1->LoadVmsMsgScenario(String(FSelVmsObj->VMS_CTLR_NMBR));
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::OnVmsSelectMessage(TMessage &Msg)
{
#if 0
    try {
        FSelVmsObj = (TVmsCtlr*)Msg.WParam;
        FRAMEVmsState1->SelVmsObj = FSelVmsObj;

        if (!FSelVmsObj) return;

        TVMSFORM0 *pSelForm = (TVMSFORM0*)Msg.LParam;
        if (pSelForm == FSelForm) return;

        if (FSelForm) FSelForm->SelectForm(false);

        FSelForm = pSelForm;
        if (FSelForm) FSelForm->SelectForm(true);

        FRAMEVmsMsgList1->LoadVmsMsgScenario(String(FSelVmsObj->VMS_CTLR_NMBR));
    } catch(...) {};
#endif
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::InitMonitoringForm()
{
#if 0
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT COUNT(1) AS CNT          \r\n"
           "  FROM TB_VMS_MONITORING        \r\n"
           " WHERE MONITORING_TYPE = :p01   \r\n";

    try
    {
        int nString(0), nFigure(0), nFormSeq(0);

        VmsManager->FLists.Lock();
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", String(FMonitoringType));
            ITSDb_SQLOpen(pADO);
            int nFormCnt = pADO->FieldByName("CNT")->AsInteger;
            if (nFormCnt > 0) return;

    sQry = "INSERT INTO TB_VMS_MONITORING (     \r\n"
           "                MONITORING_TYPE,    \r\n"
           "                MONITORING_NM,      \r\n"
           "                MONITORING_SEQ,     \r\n"
           "                VMS_CTLR_NMBR       \r\n"
           "                )                   \r\n"
           "  VALUES (                          \r\n"
           "                :p01,               \r\n"
           "                :p02,               \r\n"
           "                :p03,               \r\n"
           "                :p04                \r\n"
           "                )                   \r\n";


            ITSDb_SQLText(pADO, sQry);

            FOR_STL(TVmsCtlr*, pObj, VmsManager->FLists)
            {
                if (pObj->DEL_YN == "Y") continue;

                //String sFormName = "VMS 문자식";
                String sFormName = "VMS Text";
                if (pObj->VMS_USAG_TYPE_CD == "VUTN")   //문자식
                {
                    nFormSeq = ++nString;
                }
                else
                if (pObj->VMS_USAG_TYPE_CD == "VUTP")   //도형식
                {
                    //sFormName = "VMS 도형식";
                    sFormName = "VMS Figure";
                    nFormSeq = ++nFigure;
                }
                else continue;

                ITSDb_SQLBind(pADO, "p01", String(FMonitoringType));
                ITSDb_SQLBind(pADO, "p02", sFormName);
                ITSDb_SQLBind(pADO, "p03", String(nFormSeq));
                ITSDb_SQLBind(pADO, "p04", String(pObj->VMS_CTLR_NMBR));

                ITSDb_SQLExec(pADO);
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("VMS Monitoring screen query", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("VMS Monitoring screen query", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        VmsManager->FLists.UnLock();
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::ActivateForm(bool AActivate)
{
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::RBtn01Click(TObject *Sender)
{
    TcxRadioButton *pBtn = (TcxRadioButton *)Sender;
    if (!pBtn) return;

    if (!FListForm) return;

    int nType = pBtn->Tag;

    try
    {
        int nTop = 23;
        int nGap = 2;

        LockWindowUpdate(Handle);

        int nForms = FListForm->Count;
        for (int ii = 0; ii < nForms; ii++)
        {
             TCTV0101M *pForm = (TCTV0101M *)FListForm->Items[ii];
             if (!pForm->FObjInfo) continue;

             if (nType == 0) //상태+영상
             {
                pForm->PnlCctv->Visible = true;
                pForm->CxList->Visible = true;

                pForm->PnlCctv->Top = nTop;
                pForm->CxList->Top = nTop + pForm->PnlCctv->Height + nGap;

                pForm->Height = nTop + pForm->PnlCctv->Height + nGap + pForm->CxList->Height + nGap+1;

                pForm->Hide();
             }
             else
             if (nType == 1) //영상
             {
                pForm->PnlCctv->Visible = true;
                pForm->CxList->Visible = false;

                pForm->PnlCctv->Top = nTop;

                pForm->Height = nTop + pForm->PnlCctv->Height + nGap+1;

                pForm->Hide();
             }
             else
             if (nType == 2) //상태
             {
                pForm->PnlCctv->Visible = false;
                pForm->CxList->Visible = true;

                pForm->CxList->Top = nTop;

                pForm->Height = nTop + pForm->CxList->Height + nGap+1;

                pForm->Hide();
             }
        }
    }
    __finally
    {
        LockWindowUpdate(0);
    }

    DrawCctvForm();
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::ScrollBoxClick(TObject *Sender)
{
    ScrollBox->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::ScrollBoxMouseWheel(TObject *Sender, TShiftState Shift,
          int WheelDelta, TPoint &MousePos, bool &Handled)
{
    ScrollBox->VertScrollBar->Position -= WheelDelta;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::DrawCctvForm()
{
    int nRows = 0;
    int nCols = 0;
    int nTop  = 0;
    int nLeft = 0;
    int nTotTop, nTotLeft;
    try
    {
        LockWindowUpdate(Handle);

        ScrollBox->VertScrollBar->Range = 0;

        m_nScrollWidth = ScrollBox->Width-10;
        FCols = m_nScrollWidth / FFormWidth;

        int nForms = FListForm->Count;
        for (int ii = 0; ii < nForms; ii++)
        {
             TCTV0101M *pForm = (TCTV0101M *)FListForm->Items[ii];
             nTotTop = (nRows * pForm->Height)+(nTop*(nRows+1));
             nTotLeft = (nCols * pForm->Width)+(nLeft*(nCols+1));
             pForm->Top = nTotTop;
             pForm->Left= nTotLeft;
             pForm->FCol = nCols;
             pForm->FRow = nRows;
             if (!pForm->Showing)
                pForm->Show();

             if ((ii%FCols) == (FCols-1))
             {
                nRows++;
                nCols = 0;
             }
             else
             {
                nCols++;
             }
        }
    }
    __finally
    {
        ScrollBox->VertScrollBar->Range = ((nRows+1) * FFormHeight) + FFormHeight / 2;
        LockWindowUpdate(0);
        FReady = true;
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::ClearFormList()
{
    try
    {
        LockWindowUpdate(Handle);
        try
        {
            for (int ii = FListForm->Count-1; ii >= 0; ii--)
            {
                TCTV0101M *pForm = (TCTV0101M *)FListForm->Items[ii];
                pForm->Hide();
                FListForm->Delete(ii);
            }
            FListForm->Clear();
        }
        catch(Exception &e)
        {
        }
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

TForm* __fastcall TCTV0100M::FindCctvForm(int ACtlrNmbr)
{
    if (!FListForm) return NULL;

    int nForms = FListForm->Count;
    for (int ii = 0; ii < nForms; ii++)
    {
         TCTV0101M *pForm = (TCTV0101M *)FListForm->Items[ii];
         if (pForm->FCTLR_NMBR == ACtlrNmbr) return (TForm*)pForm;
    }

    return NULL;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::HideCctvForm()
{
    try
    {
        LockWindowUpdate(Handle);

        if (!FListForm) return;

        int nForms = FListForm->Count;
        for (int ii = 0; ii < nForms; ii++)
        {
             TCTV0101M *pForm = (TCTV0101M *)FListForm->Items[ii];
             //pForm->Hide();
             pForm->FDeleted = true;
        }
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::DeleteCctvForm()
{
    try
    {
        LockWindowUpdate(Handle);

        if (!FListForm) return;

        int nForms = FListForm->Count;
        if (nForms == 0) return;
        nForms--;
        // 마지막 화면 하나는 남겨야 한다.
        for (int idx = nForms-1; idx >= 0; idx--)
        {
             TCTV0101M *pForm = (TCTV0101M *)FListForm->Items[idx];
             if (pForm->FDeleted)
             {
                pForm->Hide();
                FListForm->Delete(idx);
             }
        }
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::RefreshCctvStatus(bool ARealtime/*=false*/)
{
    CctvCtlrManager->FLists.Lock();
    try
    {
        FOR_STL(TCctvCtlr*, pObj, CctvCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            // Image Form update start
            TCTV0101M *pForm = (TCTV0101M *)FindCctvForm(pObj->CCTV_CTLR_NMBR);
            if (pForm == NULL)
            {
                pForm = new TCTV0101M(this);
                pForm->Parent   = ScrollBox;
                pForm->FPHandle = (HWND)Handle;
                pForm->Align    = alCustom;
                pForm->Hide();

                pForm->FObjInfo         = pObj;  // 상태메모리 할당
                pForm->FCTLR_NMBR       = pObj->CCTV_CTLR_NMBR;
                pForm->LblName->Caption = pObj->ISTL_LCTN_NM;

                FListForm->Add((void*)pForm);
                FFormWidth = pForm->Width;
                FFormHeight= pForm->Height;
            }
            pForm->FDeleted = false;

            pForm->RefreshStatus();     // 상태정보 업데이트
        }
    }
    __finally
    {
        CctvCtlrManager->FLists.UnLock();
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::RefreshData()
{
    try
    {
        LockWindowUpdate(Handle);

        HideCctvForm();         // 기존 CCTV 폼을 화면에서 숨긴다.
        RefreshCctvStatus();    // CCTV 상태정보 업데이트(delete, insert)
        DeleteCctvForm();       // 기존 CCTV 목록에서 삭제된 폼을 메모리에서도 삭제한다.
        DrawCctvForm();
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::BtnSearchClick(TObject *Sender)
{
    RefreshData();

    ScrollBox->SetFocus();

    TmrImage->Interval = 300;
    TmrImage->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::TmrImageTimer(TObject *Sender)
{
    TmrImage->Enabled = false;
    TmrImage->Interval = 1000 * 60 * 4;
    SelCctvStopImage();
    TmrImage->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::SelCctvStopImage()
{
#if 0
    String sQry;

    try
    {
        LockWindowUpdate(Handle);

        int nForms = m_pFormList->Count;
        for (int ii = 0; ii < nForms; ii++)
        {
             TCTV00002 *pForm = (TCTV00002 *)m_pFormList->Items[ii];
             try {
                pForm->ImgCctv->Picture->Bitmap->FreeImage();
                //pForm->ImgCctv->Picture->Bitmap = NULL;
                pForm->ImgCctv->Picture->Assign(ImgNoData->Picture);
             } catch(...) {}
        }
    } __finally {
        LockWindowUpdate(0);
    }

    sQry = "SELECT A.CCTVID, A.COLLDT, A.IMG                                     "
           "  FROM RUTIS.CCTVIMG_BLOB A                                          "
           " WHERE (A.CCTVID, A.COLLDT) IN (SELECT CCTVID, MAX(COLLDT) AS COLLDT "
           "                                  FROM RUTIS.CCTVIMG_BLOB            "
           "                                 WHERE A.COLLDT >= SYSDATE - 15/1440 "
           "                                 GROUP BY CCTVID)                    "
           " ORDER BY A.CCTVID                                                   ";

    try
    {
        ADO->Connection = ITSDb_GetConnection();
        ClearQry(ADO);
        SetQry(ADO, sQry);
//        ParamBind(ADO, "p01", m_sIdList);
        OpenQry(ADO);
        ADO->First();

        try
        {
            while(!ADO->Eof)
            {
                String sId = ADO->FieldByName("CCTVID")->AsString;
                TCTV00002 *pForm = (TCTV00002 *)FindCctvForm(sId);
                if (pForm)
                {
                    String sCaption = pForm->Caption;

                    TStream *pStream = NULL;
                    pStream = ADO->CreateBlobStream(ADO->FieldByName("IMG"), bmRead);
                    pStream->Position = 0;
                    TJPEGImage *jp = new TJPEGImage();
                    try
                    {
                        jp->LoadFromStream(pStream);
                        pForm->ImgCctv->Picture->Assign(jp);
                    }
                    catch(...)
                    {
                        sCaption = sCaption + "[X]";
                    }
                    delete pStream;
                    delete jp;
                }

                ADO->Next();
            }
        }
        __finally
        {
            ADO->Close();
        }
    }
    catch(EDatabaseError &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch (Exception &exception)
    {
        throw Exception(String(exception.ClassName()) + exception.Message);
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::PnlCenterResize(TObject *Sender)
{
    if (!FReady) return;
    if (ScrollBox->Width-100 > FFormWidth)
    {
        if (IsFormResizing == false)
        {
            DrawCctvForm();
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::WMEnterSizeMove(TMessage &Msg)
{
    IsFormResizing = true;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0100M::WMExitSizeMove(TMessage &Msg)
{
    IsFormResizing = false;
    DrawCctvForm();
}
//---------------------------------------------------------------------------


