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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "ITSLangTransF.h"
#include "CenterCommF.h"
#include "CDSFacilityF.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 link "dxSkinMcSkin"
#pragma resource "*.dfm"

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

    FTitle = Caption;
    FReqSeq = 0;

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

    FRAMEDsrcList1->PnlBottom->Visible = false;
    FRAMEDsrcList1->Column04->Visible = true;   // IP Address
    FRAMEDsrcList1->Column05->Visible = true;   // 통신상태

}
//---------------------------------------------------------------------------

void __fastcall TDSRM020M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TDSRM020M::FormInit()
{
}
//---------------------------------------------------------------------------

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

	RdoController->Checked = true;

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

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

    int ii;
    int nRowCnt = FRAMEDsrcList1->TvList->ViewData->RecordCount;
    int nNormalCount = 0;

    for (ii = 0; ii < nRowCnt; ii++)
    {
        TcxCustomGridRow* ARow = FRAMEDsrcList1->TvList->ViewData->Rows[ii];
        if (((bool)ARow->Values[FRAMEDsrcList1->ColumnSel->Index]))
        {
            String sComm = "";
            if (!VarIsNull(ARow->Values[FRAMEDsrcList1->Column06->Index]))
                sComm = ARow->Values[FRAMEDsrcList1->Column06->Index];
            if (sComm != str_state_error)
                nNormalCount++;
        }
    }
    #if 0
    if (0 == nNormalCount)
    {
        Application->MessageBox(L"통신상태가 정상일 경우에만 제어명령을 전송 할 수 있습니다.", FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        FRAMEDsrcList1->CxList->SetFocus();
        return;
    }
    #endif

	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에 대하여 제어명령을 전송하시겠습니까??",
                                FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

    int               nRow;
    int               nResult;
    dsrc_device_code  DeviceType;
    dsrc_control_code ControlType;

    DeviceType = dsrc_device_main;
    if (RdoAnt1->Checked)
    {
        DeviceType = dsrc_device_antena1;
    }

    ControlType = dsrc_control_reset;
	if (RdoStop->Checked)
	{
        ControlType = dsrc_control_stop;
	}
    else
	if (RdoStart->Checked)
	{
        ControlType = dsrc_control_start;
	}

    CMM_ClearGridTableView(TvResult);

    BYTE                 MsgSeq;
    INT_DSRC_CONTROL_REQ ControlReq;
    memset(&ControlReq, 0x00, sizeof(ControlReq));

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

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

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

        for (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();
                TvResult->DataController->Values[nRow][ColDsrcId->Index] = sId;

                // TODO: 제어기 통신상태를 확인하고 전송하도록 하자.
                //       한패킷에 여러제어기를 합쳐서 전송할 수 있도록 하자.
                bool isCommNormal = true;//false;
                String sComm = "";
                if (!VarIsNull(ARow->Values[FRAMEDsrcList1->Column06->Index]))
                    sComm = ARow->Values[FRAMEDsrcList1->Column06->Index];
                if (sComm != str_state_error)
                    isCommNormal = true;

                if (isCommNormal)
                {
                    String sSendDate = Now().FormatString("YYYYMMDD");
                    String sSendTime = Now().FormatString("HHNNSS");

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

                    MsgSeq = (BYTE)0x90;
                    memcpy(ControlReq.CmdTime, AnsiString(sCmdTime).c_str(), INT_DSRC_MAX_DATETIME); /* 명령수행시각 */
                    memcpy(ControlReq.OperId,  AnsiString(sCmdUser).c_str(), INT_DSRC_MAX_OPER_ID);  /* 운영자 ID */
                    ControlReq.ReqSeq         = FReqSeq;
                    ControlReq.DSRC_CTLR_NMBR = sId.ToIntDef(0);
                    ControlReq.DeviceType     = DeviceType;
                    ControlReq.ControlType    = ControlType;

                    TvResult->DataController->Values[nRow][ColReqSeq->Index] = String(FReqSeq);

                    nResult = CComm_DsrcControlReq(&ControlReq);
                    if (VERR_NONE == nResult)
                    {
                        TvResult->DataController->Values[nRow][ColReqResult->Index] = "성공";
                    }
                    else
                    {
                        TvResult->DataController->Values[nRow][ColReqResult->Index] = "실패";
                    }
                    TvResult->DataController->Values[nRow][ColResResult->Index] = "응답대기";
                    FReqSeq++;
                }
                else
                {
                    TvResult->DataController->Values[nRow][ColReqSeq->Index] = "-";
                    TvResult->DataController->Values[nRow][ColReqResult->Index] = "통신이상";
                    TvResult->DataController->Values[nRow][ColResResult->Index] = "-";
                }
            }
        }
    }
    __finally
    {
        FRAMEDsrcList1->TvList->EndUpdate();
        TvResult->EndUpdate();
    }
#if 0
	dsrc_response_succ,                          /* 0: 성공 */
	dsrc_response_nack,                          /* 1: 거절 */
    dsrc_response_none,                          /* 2: 응답없음 */
#endif

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

void __fastcall TDSRM020M::OnMainFormMessage(TMessage &Msg)
{
    IPC_MSG_DATA   *RcvData = (IPC_MSG_DATA*)Msg.LParam;
    INT_SENDER     *Sender  = &RcvData->Sender;
    INT_PACKET     *Pkt     = &RcvData->Pkt;
    INT_HEAD       *head    = &Pkt->head;
    INT_DATA       *data    = &Pkt->data;
    char           *pData   = &Pkt->data.Data[0];
    BYTE            OpCode  = head->OpCode;

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

            String sResId  = String(pRseCtl->DSRC_CTLR_NMBR);
            String sResSeq = String(pRseCtl->ReqSeq);
            int    nResult = (int)pRseCtl->ResCode;
            try {
                TvResult->BeginUpdate();

                int nRowCnt = TvResult->ViewData->RecordCount;
                for (int ii = 0; ii < nRowCnt; ii++)
                {
                    TcxCustomGridRow* ARow = TvResult->ViewData->Rows[ii];
                    {
                        String sId = VarToStr(ARow->Values[ColDsrcId->Index]);
                        String sSeq= VarToStr(ARow->Values[ColReqSeq->Index]);
                        if (sResId == sId && sResSeq == sSeq)
                        {
                            String sResult = "Unknown";
                            if (nResult == (int)dsrc_response_succ) sResult = "성공";
                            else
                            if (nResult == (int)dsrc_response_nack) sResult = "실패";
                            else
                            if (nResult == (int)dsrc_response_none) sResult = "응답없음";

                            ARow->Values[ColResResult->Index] = sResult;
                            break;
                        }
                    }
                }
            }
            __finally
            {
                TvResult->EndUpdate();
            }
		}
		break;
	default:
		break;
	}/* end switch */
}
//---------------------------------------------------------------------------

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

void __fastcall TDSRM020M::ColResResultCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    TColor tColor = ACanvas->Brush->Color;
    TColor tFont  = clBlack;
    try
    {
        TColor tColor;
        String sStatus = AViewInfo->GridRecord->DisplayTexts[AViewInfo->Item->Index];
        tColor = ACanvas->Brush->Color;

        if      (sStatus.Pos("응답없음")) tColor = clRed;
        else if (sStatus.Pos("실패"))     tColor = clRed;
        else if (sStatus.Pos("응답대기")) tColor = clYellow;
        else if (sStatus.Pos("성공"))     tColor = clLime;
        else                              tColor = clGray;

        ACanvas->SetBrushColor(tColor);
        if (tColor == clRed) tFont = clWhite;
        ACanvas->Font->Color = tFont;
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

