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

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

#include "VDSM300MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxEdit"
#pragma link "cxFilter"
#pragma link "cxGraphics"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxRadioGroup"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "FRAME_VdsStateListF"
#pragma link "cxTextEdit"
#pragma link "cxDropDownEdit"
#pragma link "cxMaskEdit"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

#define UDP_TEST    0

TVDSM300M *VDSM300M = NULL;
//---------------------------------------------------------------------------
__fastcall TVDSM300M::TVDSM300M(TComponent* Owner)
    : TForm(Owner)
{
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FTitle = Caption;
    FReqSeq = 0;

    FRAMEVdsStateList1->PnlTop->Visible = false;
    FRAMEVdsStateList1->PnlBottom->Visible = false;
}
//---------------------------------------------------------------------------

void __fastcall TVDSM300M::CommClose()
{
    try
    {
        FStopImages.RemoveAll();
        TmrControlTimeout->Enabled = false;
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TVDSM300M::FormInit()
{
    PnlImage->ParentColor = false;
    PnlImage->Color = clBlack;
}
//---------------------------------------------------------------------------

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

    FRAMEVdsStateList1->UpdateList();
}
//---------------------------------------------------------------------------

void __fastcall TVDSM300M::BtnCloseClick(TObject *Sender)
{
    Close();    
}
//---------------------------------------------------------------------------

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

void __fastcall TVDSM300M::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    FRAMEVdsStateList1->OnCloseQuery(CanClose);
}
//---------------------------------------------------------------------------

bool AssignJpg(TImage *AImage, TStream *AStream)
{
    bool bResult = true;
	TJPEGImage *pJpg = new TJPEGImage();
	try
	{
		try
		{
			pJpg->LoadFromStream(AStream);
			AImage->Picture->Assign(pJpg);
		}
		catch(Exception &e)
		{
            bResult = false;
            //MERROR("MAIN AssignJpg Failed: %s, %s", AnsiString(e.ClassName()).c_str(), AnsiString(e.Message).c_str());
		}
	}
	__finally
	{
		if (pJpg) {
			delete pJpg;
		}
    }
    return bResult;
}
//---------------------------------------------------------------------------

void __fastcall TVDSM300M::OnMainFormMessage(TMessage &Msg)
{
	switch (Msg.WParam)
	{
	case WP_DB_SELECT_OK:
        if (Msg.LParam == LP_MSG_FACILITY_STTS)
        {
            FRAMEVdsStateList1->RefreshStatus();
        }
        break;
	case INT_OP_VDS_STOP_IMAGE_RES:
		{
            IPC_MSG_DATA   *RcvData = (IPC_MSG_DATA*)Msg.LParam;
            INT_VDS_STOP_IMAGE_RES *ARes = (INT_VDS_STOP_IMAGE_RES*)&RcvData->Pkt.data.Data[0];;

            if (ARes->Error != ERR_VDS_STOP_IMAGE_NORMAL)
            {
                BtnStopImage->Enabled = true;
                TmrControlTimeout->Enabled = false;
                FStopImages.RemoveAll();
                String sMsg;
                sMsg.printf(L"VDS 정지영상 요청중 오류가 발생했습니다.\r\n오류코드: %02X", ARes->Error);
                Application->MessageBox(sMsg.c_str(), BtnStopImage->Caption.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
                break;
            }

            //reMsg->Lines->Add(String(ARes->Total) + ", " + String(ARes->Current) + ", " + String(FStopImages.Size()));

            TVdsStopImage *pImage = new TVdsStopImage();
            pImage->Size = ARes->Size;
            memcpy(pImage->Data, ARes->Data, ARes->Size);
            FStopImages.Push(ARes->Current, pImage);
            //if ((ARes->Total+1) == FStopImages.Size())
            {
                BtnStopImage->Enabled = true;
                TmrControlTimeout->Enabled = false;

                AnsiString sFileName;
                sFileName.printf("%s%d-%d.jpg", AnsiString(g_sTempDir).c_str(), ARes->VDS_CTLR_NMBR, GetTickCount());
                try {
                    DeleteFile(sFileName);
                } catch(Exception &e) {}

                try {
                    FILE *fp = fopen(sFileName.c_str(), "wb+");
                    if (fp)
                    {
                        FOR_STL(TVdsStopImage*, pObj, FStopImages)
                        {
                            //fwrite(pObj->Data+2, pObj->Size-2, 1, fp);
                            fwrite(pObj->Data, pObj->Size, 1, fp);
                            break;
                        }
                        fclose(fp);
                    }
                    Image1->Picture->LoadFromFile(sFileName);
                } catch(Exception &e) {
                    ShowMessage(e.Message);
                }
                FStopImages.RemoveAll();
            }
		}
		break;
	default:
		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TVDSM300M::BtnResetClick(TObject *Sender)
{
    TVdsCtlr *pObj = VdsCtlrManager->FLists.Find(EdNmbr->Text);
    if (!pObj) return;

    String sTitle = BtnReset->Caption;
    String sMsg   = "";

#if UDP_TEST
#else
    if (pObj->STATE.Comm != vds_normal)
    {
        sMsg = lblText3->Caption;//"현재 통신이 비정상인 VDS는 선택하실 수 없습니다.\r\n통신상태가 정상인 VDS를 선택하십시요.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
#endif

    int nCmdIdx;
    nCmdIdx = 2;
    sMsg = lblText6->Caption + "\r\n" + cxLabel9->Caption;//"선택하신 VDS에 VDS 제어기 리셋 명령을 전송하시겠습니까?\r\n(통신상태에 따라 명령이 실행되지 않을 수 있습니다.)";

    if (Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_YESNO|MB_ICONWARNING|MB_APPLMODAL) != IDYES) return;

    int result;
    String sCmdUser = g_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

    // 제어기 리셋
    INT_VDS_RESET_REQ VdsReset;
    BYTE              MsgSeq;

    memset(&VdsReset, 0x00, sizeof(VdsReset));

    MsgSeq = (BYTE)0x20;
    memcpy(VdsReset.CmdTime, AnsiString(sCmdTime).c_str(), INT_VDS_MAX_DATETIME); /* 명령수행시각 */
    memcpy(VdsReset.OperId,  AnsiString(sCmdUser).c_str(), INT_VDS_MAX_OPER_ID);  /* 운영자 ID */
    VdsReset.VDS_CTLR_NMBR = pObj->VDS_CTLR_NMBR.ToIntDef(0);

    result = CComm_VdsResetReq(&VdsReset, MsgSeq);
    if (VERR_NONE == result)
    {
        //VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "1", sCmdUser);
    }
    else
    {
        //VmsCtlrManager->InsVmsControlHs(sCmdTime, sVmsNmbr, "V03", "Reset", "0", sCmdUser);
    }

    sMsg = lblText7->Caption;//"VDS로 제어기 리셋 명령을 요청하였습니다.";
    Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
}
//---------------------------------------------------------------------------
void __fastcall TVDSM300M::BtnStopImageClick(TObject *Sender)
{
    TVdsCtlr *pObj = VdsCtlrManager->FLists.Find(EdNmbr->Text);
    if (!pObj) return;

    String sTitle = BtnStopImage->Caption;
    String sMsg   = "";

#if UDP_TEST
#else
    if (pObj->STATE.Comm != vds_normal)
    {
        sMsg = lblText3->Caption;//"현재 통신이 비정상인 VDS는 선택하실 수 없습니다.\r\n통신상태가 정상인 VDS를 선택하십시요.";
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
#endif

    String sCmraNo = ITSUtil_GetCode(CbVDS_CMRA_NO->Text);      // 카메라 번호
    if (CbVDS_CMRA_NO->ItemIndex < 0)
    {
        sMsg = cxLabel4->Caption;
        Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    FStopImages.RemoveAll();

    int result;
    String sCmdUser = g_pLOGIN->sUserId;
    String sCmdTime = Now().FormatString("yyyymmddhhnnss");

    if (Image1->Picture)
    {
        Image1->Picture->Assign(NULL);
    }
    // VDS 카메라 정지영상 요청
    INT_VDS_STOP_IMAGE_REQ VdsImage;
    BYTE                   MsgSeq;

    memset(&VdsImage, 0x00, sizeof(VdsImage));

    MsgSeq = (BYTE)0x30;
    memcpy(VdsImage.CmdTime, AnsiString(sCmdTime).c_str(), INT_VDS_MAX_DATETIME); /* 명령수행시각 */
    memcpy(VdsImage.OperId,  AnsiString(sCmdUser).c_str(), INT_VDS_MAX_OPER_ID);  /* 운영자 ID */
    VdsImage.VDS_CTLR_NMBR = pObj->VDS_CTLR_NMBR.ToIntDef(0);
    sCmraNo = "0";//Edit1->Text.Trim();
    VdsImage.CameraNo      = (BYTE)sCmraNo.ToIntDef(0);

    result = CComm_VdsStopImageReq(&VdsImage, MsgSeq);

    BtnStopImage->Enabled = false;
    TmrControlTimeout->Tag = 1;
    TmrControlTimeout->Enabled = true;

    sMsg = cxLabel5->Caption;//"VDS로 제어기 리셋 명령을 요청하였습니다.";
    //Application->MessageBox(sMsg.c_str(), sTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
}
//---------------------------------------------------------------------------

void __fastcall TVDSM300M::FRAMEVdsStateList1TvListCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
	if (!ACellViewInfo) return;
	int nRow = FRAMEVdsStateList1->TvList->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    String NMBR = "";
    String ID   = "";
    String NAME = "";
    bool bCmdEnabled = false;
    int nMemPtr = FRAMEVdsStateList1->TvList->DataController->Values[nRow][FRAMEVdsStateList1->Column99->Index];
    TVdsCtlr* pObj = (TVdsCtlr*)nMemPtr;
    if (pObj)
    {
        NMBR = pObj->VDS_CTLR_NMBR;
        ID   = pObj->VDS_CTLR_ID;
        NAME = pObj->VDS_NM;
        if (pObj->STATE.Comm == vds_normal)
        {
            bCmdEnabled = true;
        }
    }

#if UDP_TEST
    bCmdEnabled = true;
#endif
    EdNmbr->Text = NMBR;
    EdVdsId->Text = ID;
    EdVdsNm->Text = NAME;

    BtnReset->Enabled = bCmdEnabled;
    BtnStopImage->Enabled = bCmdEnabled;

    CbVDS_CMRA_NO->Properties->Items->Clear();

    TVdsCtlr *pVds;
    pVds = VdsCtlrManager->FLists.Find(NMBR);
    if (!pVds) return;
    FOR_STL(TVdsCmra*, pCmra, pVds->FCmras)
    {
        String sId = String(pCmra->VDS_CMRA_NO);
        String sNm = pCmra->VDS_CMRA_NM;
        CbVDS_CMRA_NO->Properties->Items->Add("[" + sId + "] " + sNm);
    }
    CbVDS_CMRA_NO->ItemIndex = 0;

    if (Image1->Picture)
    {
        Image1->Picture->Assign(NULL);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM300M::TmrControlTimeoutTimer(TObject *Sender)
{
    TmrControlTimeout->Enabled = false;
    if (TmrControlTimeout->Tag == 1)
    {
        String sMsg = cxLabel6->Caption;
        Application->MessageBox(sMsg.c_str(), BtnStopImage->Caption.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FStopImages.RemoveAll();
        BtnStopImage->Enabled = true;
    }
}
//---------------------------------------------------------------------------

