#include "cmwcompioout.h"
#include "logic.h"
#include "gui.h"
CMWCompIOOut::CMWCompIOOut(QWidget *parent, int iStartIO, int iEndIO)
    : CMWidget(parent)
{
    m_pGridLayOut=new QGridLayout(this);
    setLayout(m_pGridLayOut);
    Q_ASSERT(iEndIO>=iStartIO);
    m_vIO.resize(iEndIO-iStartIO+1);
    int iIndex=0;
    for(int i=iStartIO;i<=iEndIO;i++)
    {
        IOCTRL& ctrl=m_vIO[iIndex];
        ctrl.iIOIndex=i;

        CCtrlButtonID* pButton=new CCtrlButtonID(this,iIndex);

            pButton->setMinimumHeight(50);
            pButton->setMaximumWidth(220 );
         pButton->setSizePolicy(QSizePolicy::Fixed,
         QSizePolicy::Fixed);
         pButton->setFixedSize(QSize(230,50));
        pButton->setCheckable(true);
        ctrl.pButton=pButton;

        connect(pButton,
                SIGNAL(MClick_Signal(int32_t)),
                this,SLOT(ButtonClicked(int32_t)));
        iIndex++;
    }
}

void CMWCompIOOut::MInit()
{
    CIO* pIO=GET_CHDIRECT(IO_OUTPUT,CIO);
    Q_ASSERT(pIO);
    int isize=m_vIO.size();
    for(int i=0;i<isize;i++)
    {
        IOCTRL& ctrl=m_vIO[i];
        ctrl.pButton->setText(QString::number(ctrl.iIOIndex)+
                              " "
                              +pIO->m_io[ctrl.iIOIndex].singlename + " " + QString::number(pIO->m_io[ctrl.iIOIndex].ioIndex));
        m_pGridLayOut->addWidget(ctrl.pButton,i%(isize/2),i/(isize/2));
    }
}

void CMWCompIOOut::MTimeFresh()
{
    CIO* pIO=GET_CHDIRECT(IO_OUTPUT,CIO);
    Q_ASSERT(pIO);
    int isize=m_vIO.size();
    for(int i=0;i<isize;i++)
    {
        IOCTRL& ctrl=m_vIO[i];
        int iIndex=ctrl.iIOIndex;
        if(iIndex>=pIO->m_iIOcnt) return;
        bool bCheck=int(pIO->m_io[iIndex].fdata)?true:false;
        if(bCheck!=ctrl.pButton->isChecked())
        {
            ctrl.pButton->setChecked(bCheck);
        }
    }
}

void CMWCompIOOut::showEvent(QShowEvent *pEvent)
{
    CMWidget::showEvent(pEvent);
}

void CMWCompIOOut::hideEvent(QHideEvent *event)
{
    CMWidget::hideEvent(event);
}

void CMWCompIOOut::ButtonClicked(int32_t iID)
{
    IOCTRL& ctrl=m_vIO[iID];
    CIO* pIO=GET_CHDIRECT(IO_OUTPUT,CIO);
    Q_ASSERT(pIO);
    int iCheck=int(pIO->m_io[ctrl.iIOIndex].fdata)?0:1;

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,QObject::trUtf8("Set Output IO Sig"),
                          QVariantList()
                          <<MOTOR_DRIVER<<CMotorDriver::SETIO
                          <<IO_OUTPUT<<ctrl.iIOIndex<<iCheck,0);
    m_gSystem.start_test(SM_MAIN, msgqueue);

}

