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

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

#include "CTV0300MF.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 link "cxClasses"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxEdit"
#pragma link "cxFilter"
#pragma link "cxGrid"
#pragma link "cxGridBandedTableView"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma resource "*.dfm"
TCTV0300M *CTV0300M = NULL;

//---------------------------------------------------------------------------
__fastcall TCTV0300M::TCTV0300M(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;
}
//---------------------------------------------------------------------------

void __fastcall TCTV0300M::CommClose()
{
    try
    {
        SAFE_DELETE(FListForm);

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

void __fastcall TCTV0300M::FormCreate(TObject *Sender)
{
    InitMonitoringForm();
}
//---------------------------------------------------------------------------

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

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

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

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

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

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

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

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

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

void __fastcall TCTV0300M::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 TCTV0300M::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 TCTV0300M::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 TCTV0300M::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 TCTV0300M::ActivateForm(bool AActivate)
{
}
//---------------------------------------------------------------------------

void __fastcall TCTV0300M::RefreshCctvStatus(bool ARealtime/*=false*/)
{
#if 0
    m_nListCommErr = 0;
    m_nListHamcErr = 0;
    m_nListCtrlErr = 0;

    ClearGridTableView(TvList);

    int nCctvCnt = ITSObjCctv_GetCount();
    TList *pCctvList = ITSObjCctv_GetList();
    if (!pCctvList) return;

    TcxGridDataController *pGDC = (TcxGridDataController *)TvList->DataController;
    try
    {
        TvList->BeginUpdate();
        pGDC->BeginUpdate();
        for (int ii = 0; ii < nCctvCnt; ii++)
        {
            TObjCctv *pInfo = (TObjCctv*)pCctvList->Items[ii];
            if  (pInfo->CenterId != CenterId) continue;
            if (!pInfo->Installed) continue;

            int nRow = pGDC->AppendRecord();

            pGDC->Values[nRow][ColId->Index] = pInfo->Id;
            pGDC->Values[nRow][ColName->Index] = pInfo->Name;

            if (pInfo->Comm == INT_STATE_NORMAL)
            {
                pGDC->Values[nRow][ColCommS->Index] = "정상";

                // 함체 이상여부 체크
                if (pInfo->Door == INT_STATE_OPEN)
                {
                    pGDC->Values[nRow][ColHamS->Index] = "이상";
                    m_nListHamcErr++;
                }
                else
                if (pInfo->Door == INT_STATE_CLOSE)
                {
                    pGDC->Values[nRow][ColHamS->Index] = "정상";
                }
                else
                {
                    pGDC->Values[nRow][ColHamS->Index] = "-?-";
                }

                if (pInfo->Door == INT_STATE_UNKNOWN)
                {
                    // 알수 없음 처리
                    pGDC->Values[nRow][ColTemp->Index] = "-?-";
                    pGDC->Values[nRow][ColVolt->Index] = "-?-";
                    pGDC->Values[nRow][ColVoltOut->Index] = "-?-";

                    pGDC->Values[nRow][ColCtrlS->Index] = "-?-";
                }
                else
                {
                    pGDC->Values[nRow][ColTemp->Index] = String(pInfo->Temp);
                    pGDC->Values[nRow][ColVolt->Index] = String(pInfo->Voltage);
                    pGDC->Values[nRow][ColVoltOut->Index] = String(pInfo->VoltageOut);

                    // 제어기 이상여부 체크
                    if (pInfo->Camera    == INT_STATE_ERROR ||
                        pInfo->SetString == INT_STATE_ERROR ||
                        pInfo->Battery   == INT_STATE_ERROR)
                    {
                        pGDC->Values[nRow][ColCtrlS->Index] = "이상";

                        m_nListCtrlErr++;
                    }
                    else
                    {
                        pGDC->Values[nRow][ColCtrlS->Index] = "정상";
                    }
                }

                if (pInfo->Door == INT_STATE_OPEN || pInfo->Door == INT_STATE_CLOSE)
                {
                    pGDC->Values[nRow][ColDoorS->Index] = pInfo->Door == INT_STATE_OPEN ? "열림" : "닫힘";
                }
                else
                {
                    pGDC->Values[nRow][ColDoorS->Index] = "-?-";
                }

                if (pInfo->Fan == INT_STATE_STOP || pInfo->Fan == INT_STATE_RUN)
                {
                    pGDC->Values[nRow][ColFanS->Index] = pInfo->Fan == INT_STATE_STOP ? "정지" : "동작";
                }
                else
                {
                    pGDC->Values[nRow][ColFanS->Index] = "-?-";
                }

                if (pInfo->Heater == INT_STATE_STOP || pInfo->Heater == INT_STATE_RUN)
                {
                    pGDC->Values[nRow][ColHeaterS->Index] = pInfo->Heater == INT_STATE_STOP ? "정지" : "동작";
                }
                else
                {
                    pGDC->Values[nRow][ColHeaterS->Index] = "-?-";
                }

                if (pInfo->Camera == INT_STATE_NORMAL || pInfo->Camera == INT_STATE_ERROR)
                {
                    pGDC->Values[nRow][ColCamS->Index] = pInfo->Camera == INT_STATE_ERROR ? "장애" : "정상";
                }
                else
                {
                    pGDC->Values[nRow][ColCamS->Index] = "-?-";
                }

                if (pInfo->SetString == INT_STATE_NORMAL || pInfo->SetString == INT_STATE_ERROR)
                {
                    pGDC->Values[nRow][ColTextS->Index] = pInfo->SetString == INT_STATE_ERROR ? "장애" : "정상";
                }
                else
                {
                    pGDC->Values[nRow][ColTextS->Index] = "-?-";
                }

                if (pInfo->Battery == INT_STATE_NORMAL || pInfo->Battery == INT_STATE_ERROR)
                {
                    pGDC->Values[nRow][ColBattS->Index] = pInfo->Battery == INT_STATE_ERROR ? "장애" : "정상";
                }
                else
                {
                    pGDC->Values[nRow][ColBattS->Index] = "-?-";
                }


#if 0
                pGDC->Values[nRow][ColDoorS->Index]   = pInfo->Door    == INT_STATE_OPEN   ? "열림" : "닫힘";
                pGDC->Values[nRow][ColFanS->Index]    = pInfo->Fan     == INT_STATE_STOP   ? "정지" : "동작";
                pGDC->Values[nRow][ColHeaterS->Index] = pInfo->Heater  == INT_STATE_STOP   ? "정지" : "동작";

                pGDC->Values[nRow][ColCamS->Index]  = pInfo->Camera    == INT_STATE_ERROR  ? "장애" : "정상";
                pGDC->Values[nRow][ColTextS->Index] = pInfo->SetString == INT_STATE_ERROR  ? "장애" : "정상";
                pGDC->Values[nRow][ColBattS->Index] = pInfo->Battery   == INT_STATE_ERROR  ? "장애" : "정상";

                pGDC->Values[nRow][ColTemp->Index] = String(pInfo->Temp);
                pGDC->Values[nRow][ColVolt->Index] = String(pInfo->Voltage);
                pGDC->Values[nRow][ColVoltOut->Index] = String(pInfo->VoltageOut);
#endif
            }
            else
            {
                m_nListCommErr++;

                pGDC->Values[nRow][ColCommS->Index]   = "장애";
                pGDC->Values[nRow][ColHamS->Index]    = "-";
                pGDC->Values[nRow][ColCtrlS->Index]   = "-";

                pGDC->Values[nRow][ColDoorS->Index]   = "-";
                pGDC->Values[nRow][ColFanS->Index]    = "-";
                pGDC->Values[nRow][ColHeaterS->Index] = "-";

                pGDC->Values[nRow][ColCamS->Index]    = "-";
                pGDC->Values[nRow][ColTextS->Index]   = "-";
                pGDC->Values[nRow][ColBattS->Index]   = "-";

                pGDC->Values[nRow][ColTemp->Index]    = "-";
                pGDC->Values[nRow][ColVolt->Index]    = "-";
                pGDC->Values[nRow][ColVoltOut->Index]    = "-";
            }

            pGDC->Values[nRow][ColFanOn->Index]     = String(pInfo->SetFanOnTemp);
            pGDC->Values[nRow][ColFanOff->Index]    = String(pInfo->SetFanOffTemp);
            pGDC->Values[nRow][ColHeaterOn->Index]  = String(pInfo->SetHeaterOnTemp);
            pGDC->Values[nRow][ColHeaterOff->Index] = String(pInfo->SetHeaterOffTemp);
        }
    }
    __finally
    {
        pGDC->EndUpdate();
        TvList->DataController->Summary->Recalculate();
        TvList->EndUpdate();
        if (pGDC->RecordCount > 0) pGDC->FocusedRecordIndex = 0;
    }

    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();
    }
#endif
}
//---------------------------------------------------------------------------

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

        RefreshCctvStatus();    // CCTV 상태정보 업데이트(delete, insert)
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TCTV0300M::BtnSearchClick(TObject *Sender)
{
    RefreshData();
}
//---------------------------------------------------------------------------

void __fastcall TCTV0300M::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 TCTV0300M::WMEnterSizeMove(TMessage &Msg)
{
    IsFormResizing = true;
}
//---------------------------------------------------------------------------

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


