#include "cmwcalibeampos.h"
#include "ui_cmwcalibeampos.h"
#include "logic.h"
CMWCaliBeamPos::CMWCaliBeamPos(QWidget *parent) :
    CMWidget(parent),
    ui(new Ui::CMWCaliBeamPos)
{
    ui->setupUi(this);
    m_dCurWidth = -1;
}

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

void CMWCaliBeamPos::MFresh()
{
    CLaserPath* pPath = GET_CHDIRECT(LASERPATH_D_WIDE, CLaserPath);
    Q_ASSERT(pPath);
    int isize = pPath->m_mBeamPos.size();
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(isize);
    LPATHBEAMPOSMAP::iterator ii = pPath->m_mBeamPos.begin();
    int i = 0;
    for (; ii != pPath->m_mBeamPos.end(); ii++) {
        QTableWidgetItem* pitem =
            new QTableWidgetItem(QString::number(ii.key() / 1000.0, 'f', 3));
        ui->tableWidget->setItem(i, 0, pitem);
        pitem = new QTableWidgetItem(QString::number(*ii, 'f', 3));
        ui->tableWidget->setItem(i, 1, pitem);
        i++;
    }
}

void CMWCaliBeamPos::MApply()
{
    CLaserPath* pPath = GET_CHDIRECT(LASERPATH_D_WIDE, CLaserPath);
    Q_ASSERT(pPath);
    int isize = ui->tableWidget->rowCount();
    pPath->m_mBeamPos.clear();
    for (int i = 0; i < isize; i++) {
        QTableWidgetItem* pitem = ui->tableWidget->item(i, 0);
        int iwidth = pitem->text().toDouble() * 1000;
        pitem = ui->tableWidget->item(i, 1);
        pPath->m_mBeamPos[iwidth] = pitem->text().toDouble();
    }
}

void CMWCaliBeamPos::on_tableWidget_cellClicked(int row, int column)
{
    UNUSED(column);
    m_dCurWidth = ui->tableWidget->item(row, 0)->text().toDouble();
    ui->lineEdit_Width->setText(ui->tableWidget->item(row, 0)->text());
    ui->lineEdit_Pos->setText(ui->tableWidget->item(row, 1)->text());
}

void CMWCaliBeamPos::on_pushButton_Del_clicked()
{
    CLaserPath* pPath = GET_CHDIRECT(LASERPATH_D_WIDE, CLaserPath);
    Q_ASSERT(pPath);
    pPath->DelFromBeamPosMap(m_dCurWidth);
    MFresh();
}

void CMWCaliBeamPos::on_pushButton_Add_clicked()
{
    CLaserPath* pPath = GET_CHDIRECT(LASERPATH_D_WIDE, CLaserPath);
    Q_ASSERT(pPath);
    double dWidth = ui->lineEdit_Width->text().toDouble();
    double dPos = ui->lineEdit_Pos->text().toDouble();
    pPath->AddToBeamPosMap(dWidth, dPos);
    MFresh();
}

void CMWCaliBeamPos::on_pushButton_Move_clicked()
{
    int iPos = static_cast<int>(ui->lineEdit_Pos->text().toDouble());
    V_MsgQueue msgqueue;

    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Move Gripper Sig"),
                          QVariantList() << HGRIPPER_DRIVER
                          << CDHGripperRS485::MOVEPOS
                          << iPos);
    m_gSystem.start_test(SM_MAIN, msgqueue, false);
}
