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

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

#include "DSRM020MF.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 resource "*.dfm"

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

    FTitle = "DSRC-RSE 제어";
    FReqSeq = 0;

    TvResult->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<제어전송결과>";

    FRAMEDsrcList1->PnlBottom->Visible = false;
}
//---------------------------------------------------------------------------

/*
 * 닫기버튼 이나 x버튼 클릭시 공통으로 처리하는 로직이들어간다..
 * Form과 DataModule class를 delete시킨다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TDSRM020M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

/*
 * Form을 보여줄때 호출되는 event 메서드이다.
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TDSRM020M::FormShow(TObject *Sender)
{
    Refresh();
    FormInit();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TDSRM020M::FormInit()
{
}
//---------------------------------------------------------------------------

/*
 * Form이 Show되고 난 후 최초 1회 수행되는 타이머 이벤트
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TDSRM020M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;

	RdoController->Checked = true;

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

/*
 * Close 버튼 클릭 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TDSRM020M::BtnCloseClick(TObject *Sender)
{
    Close();    
}
//---------------------------------------------------------------------------

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

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

void __fastcall TDSRM020M::BtnControlClick(TObject *Sender)
{
    int nSelects = CMM_GetCheckCount(FRAMEDsrcList1->TvList, FRAMEDsrcList1->ColumnSel->Index);
    if (0 == nSelects)
    {
        Application->MessageBox(L"제어 목록을 선택하지 않았습니다.", FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        FRAMEDsrcList1->CxList->SetFocus();
        return;
    }

	if (!RdoController->Checked && !RdoAnt1->Checked)
	{
        Application->MessageBox(L"장치 유형을 선택하지 않았습니다.\r\n장치 유형을 선택하세요.", FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
		return;
	}

	if (!RdoReset->Checked && !RdoStop->Checked && !RdoStart->Checked)
	{
        Application->MessageBox(L"제어 유형을 선택하지 않았습니다.\r\n제어 유형을 선택하세요.", FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
		return;
	}

    if (Application->MessageBox(L"제어전송확인\r\n선택한 DSRC-RSE에 대하여 제어명령을 전송하시겠습니까??",
                                FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

    int                     nRow;
    int                     nResult;
    EN_INT_RSE_DEVICE_CODE  DeviceType;
    EN_INT_RSE_CONTROL_CODE ControlType;

    DeviceType = INT_RSE_DEVICE_MAIN;
    if (RdoAnt1->Checked)
    {
        DeviceType = INT_RSE_DEVICE_ATN1;
    }

    ControlType = INT_RSE_CONTROL_RESET;
	if (RdoStop->Checked)
	{
        ControlType = INT_RSE_CONTROL_STOP;
	}
    else
	if (RdoStart->Checked)
	{
        ControlType = INT_RSE_CONTROL_START;
	}

    CMM_ClearGridTableView(TvResult);

    INT_RSE_CONTROL_REQ RseCtl;
    memset(&RseCtl, 0x00, sizeof(RseCtl));

    try
    {
        FRAMEDsrcList1->TvList->BeginUpdate();

        int nRowCnt = FRAMEDsrcList1->TvList->ViewData->RecordCount;

        for (int ii = 0; ii < nRowCnt; ii++)
        {
            TcxCustomGridRow* ARow = FRAMEDsrcList1->TvList->ViewData->Rows[ii];
            if (((bool)ARow->Values[FRAMEDsrcList1->ColumnSel->Index]))
            {
                String sId = VarToStr(ARow->Values[FRAMEDsrcList1->Column01->Index]);

                nRow = TvResult->DataController->AppendRecord();

        		AnsiString DesProcessID = "DSRC01";
                String sSendDate = Now().FormatString("YYYYMMDD");
                String sSendTime = Now().FormatString("HHNNSS");

                RseCtl.Head.Seq   = FReqSeq++;
                RseCtl.Head.RseId = sId.ToIntDef(0);
                RseCtl.Data.SendDate = sSendDate.ToIntDef(0);
                RseCtl.Data.SendTime = sSendTime.ToIntDef(0);

                RseCtl.Data.DeviceType  = DeviceType;
                RseCtl.Data.ControlType = ControlType;

                nResult = VComm_RseCtlReq(&RseCtl);

                TvResult->DataController->Values[nRow][ColResult1->Index] = sId;
                TvResult->DataController->Values[nRow][ColResult2->Index] = String(RseCtl.Head.Seq);

                if (VERR_NONE == nResult)
                {
                    TvResult->DataController->Values[nRow][ColResult3->Index] = "성공";
                }
                else
                {
                    TvResult->DataController->Values[nRow][ColResult3->Index] = "실패";
                }
                TvResult->DataController->Values[nRow][ColResult4->Index] = "응답대기";
            }
        }
    }
    __finally
    {
        FRAMEDsrcList1->TvList->EndUpdate();
    }
#if 0
	INT_RSE_RESPONSE_SUCC,                       /* 0: 성공 */
	INT_RSE_RESPONSE_NACK,                       /* 1: 거절 */
    INT_RSE_RESPONSE_NONE                        /* 2: 응답없음 */
#endif

    Application->MessageBox(L"제어명령을 전송 하였습니다.", FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
}
//---------------------------------------------------------------------------

/*
 * 메인폼에서 데이터를 수신시 발생하는 이벤트 핸들러
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TDSRM020M::OnMainFormMessage(TMessage &Msg)
{
#if 0
    IPCUDPMESSAGESTRUCT *pMsg;      // 메시지 구조체
    IPCUDPDATASTRUCT    *pPkt;      // 내부 통신 패킷 구조체
    UNION_INT_DATA      *pData;     // 내부 통신 데이터부 구조체

	pMsg  = (IPCUDPMESSAGESTRUCT *)Msg.LParam;
	pPkt  = &pMsg->Frame;
	pData = &pPkt->Data.unData;

	switch (Msg.WParam)
	{
	case INT_OP_RSE_CONTROL_RES:    /* 0xC1, RSE 제어정보 응답 */
		{
			INT_RSE_CONTROL_RES *pRseCtl;
			pRseCtl = (INT_RSE_CONTROL_RES *)pData;

            String sResId  = String(pRseCtl->Head.RseId);
            String sResSeq = String(pRseCtl->Head.Seq);
            int    nResult = pRseCtl->Data.ResType;
            try {
                TvResult->BeginUpdate();

                int nRowCnt = TvResult->ViewData->RecordCount;

                for (int ii = 0; ii < nRowCnt; ii++)
                {
                    TcxCustomGridRow* ARow = FRAMEDsrcList1->TvList->ViewData->Rows[ii];
                    if (((bool)ARow->Values[FRAMEDsrcList1->ColumnSel->Index]))
                    {
                        String sId = VarToStr(ARow->Values[ColResult1->Index]);
                        String sSeq= VarToStr(ARow->Values[ColResult2->Index]);
                        if (sResId == sId && sResSeq == sSeq)
                        {
                            String sResult = "Unknown";
                            if (nResult == (int)INT_RSE_RESPONSE_SUCC) sResult = "성공";
                            else
                            if (nResult == (int)INT_RSE_RESPONSE_NACK) sResult = "실패";
                            else
                            if (nResult == (int)INT_RSE_RESPONSE_NONE) sResult = "응답없음";

                            ARow->Values[ColResult4->Index] = sResult;
                            break;
                        }
                    }
                }
            }
            __finally
            {
                TvResult->EndUpdate();
            }
#if 0

			ProcLog(CENTER_LOG_DATA, "RSE_CONTROL_RES");

			ProcLog(CENTER_LOG_DATA, "Seq: %d", pRseCtl->Head.Seq);
			ProcLog(CENTER_LOG_DATA, "RseId: %d", pRseCtl->Head.RseId);

			ProcLog(CENTER_LOG_DATA, "SendDate: %d", pRseCtl->Data.SendDate);
			ProcLog(CENTER_LOG_DATA, "SendTime: %d", pRseCtl->Data.SendTime);
			ProcLog(CENTER_LOG_DATA, "ResType: %d", pRseCtl->Data.ResType);
#endif
		}
		break;
	default:
		break;
	}/* end switch */
#endif
}
//---------------------------------------------------------------------------

void __fastcall TDSRM020M::RdoControllerClick(TObject *Sender)
{
	RdoStop->Enabled  = false;
	RdoStart->Enabled = false;

	RdoReset->Enabled = true;
    RdoReset->Checked = true;
}
//---------------------------------------------------------------------------

void __fastcall TDSRM020M::RdoAnt1Click(TObject *Sender)
{
	RdoReset->Enabled = false;

	RdoStop->Enabled  = true;
	RdoStart->Enabled = true;
	RdoStop->Checked  = true;
}
//---------------------------------------------------------------------------

