#include "cdlgterminal.h"
#include "ui_cdlgterminal.h"
#include <QListWidgetItem>
#include "logic.h"
CDlgTerminal::CDlgTerminal(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CDlgTerminal)
{
    ui->setupUi(this);
}

CDlgTerminal::~CDlgTerminal()
{
    delete ui;
}

void CDlgTerminal::hideEvent(QHideEvent *)
{
    ui->comboBox_Command->clear();
}

void CDlgTerminal::on_pushButton_Send_clicked()
{
    if(!m_gSystem.IsAllSMStopped())
    {
        AddResponse(tr("Must stop before send command"));
        return;
    }
    QString str=ui->comboBox_Command->currentText();
    if(str.length()<=2||str[1]!=':')
    {
        AddResponse(tr("Unidentity command."));
        return;
    }
    try
    {
        int iCardID=0;
        if(str[0]=='M') { iCardID= MOTOR_DRIVER;}
        else if(str[0]=='L') { iCardID= LASER_DRIVER;}
        else if(str[0]=='I') { iCardID= LIGHT_DRIVER_DIRECT;}
        else{iCardID=0;}

        CDriverCard* pCard=GET_CARD(iCardID,CDriverCard);
        char ch[RESPONSELENGTH]={0};
        if(pCard)
        {
            str.remove(0,2);
            MqDebug()<<str;
            pCard->SendCommand(str.toLatin1().data(),ch);
            QString r=ch;
            if(!strlen(ch))r=tr("No response.");
            AddResponse(r);
            str=ui->comboBox_Command->currentText();
            if(ui->comboBox_Command->findText(str)==-1)
            {
                ui->comboBox_Command->addItem(str);
            }
        }
        else
        {
            AddResponse(tr("Unidentity command."));
        }
    }
    catch(QString& s)
    {
        AddResponse(s);
    }
}

void CDlgTerminal::AddResponse(QString &str)
{
    QListWidgetItem* pItem;
    pItem=new QListWidgetItem(ui->comboBox_Command->currentText());
    ui->listWidget_Response->addItem(pItem);
    pItem=new QListWidgetItem(str);
    pItem->setBackgroundColor(Qt::darkYellow);
    pItem->setForeground(Qt::white);
    ui->listWidget_Response->addItem(pItem);
}

void CDlgTerminal::on_pushButton_Clear_clicked()
{
    ui->listWidget_Response->clear();
}
