#include "bmsservicepage.h"
#include "ui_bmsservicepage.h"
#include <QTimer>
//#include "widgets/historylineedit.h"

BmsServicePage::BmsServicePage(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::BmsServicePage)
{
    ui->setupUi(this);

    connect(ui->helpButton, &QPushButton::clicked, this, &BmsServicePage::on_helpButton_clicked);
    connect(ui->sendButton, &QPushButton::clicked, this, &BmsServicePage::on_sendButton_clicked);
    connect(ui->terminalEdit, &HistoryLineEditBox::enterClicked, this, &BmsServicePage::on_sendButton_clicked);
    //connect(ui->terminalEdit, &HistoryLineEditBox::upClicked, this, &BmsServicePage::onUpButtonClicked);
    //connect(ui->terminalEdit, &HistoryLineEditBox::downClicked, this, &BmsServicePage::onDownButtonClicked);

    connect(ui->clearButton, &QPushButton::clicked, this, &BmsServicePage::on_clearButton_clicked);
}

BmsServicePage::~BmsServicePage()
{
    delete ui;
}
/*
void BmsServicePage::onUpButtonClicked()
{
    ui->terminalEdit->
}

void BmsServicePage::onDownButtonClicked()
{

}
*/

void BmsServicePage::on_clearButton_clicked()
{
    clearTerminal();
}

void BmsServicePage::clearTerminal()
{
    ui->terminalBrowser->clear();
}

BMSInterface *BmsServicePage::bms() const
{
    return mDieBieMS;
}

void BmsServicePage::setDieBieMS(BMSInterface *dieBieMS)
{
    mDieBieMS = dieBieMS;

    if (mDieBieMS) {
        connect(mDieBieMS->commands(), SIGNAL(printReceived(QString)), this, SLOT(printReceived(QString)));
    }
}

void BmsServicePage::printReceived(QString str)
{
    ui->terminalBrowser->append(str);
}

//*
bool BmsServicePage::eventFilter(QObject *O, QEvent *E)
{
    if(O == ui->terminalEdit)
    {
        if(E->type() == QKeyEvent::KeyPress)
        {
            QKeyEvent *pkey = (QKeyEvent *)E;
            if( pkey->key()==Qt::Key_Enter || pkey->key()==Qt::Key_Return)
            {
                int a = 0;
                    return true;
            }
        }
    }
    return QWidget::eventFilter(O,E);
}

void BmsServicePage::on_sendButton_clicked()
{
    if (mDieBieMS) {
        mDieBieMS->commands()->sendTerminalCmd(ui->terminalEdit->text());
        ui->terminalEdit->clear();
    }
}

void BmsServicePage::on_helpButton_clicked()
{
    if (mDieBieMS) {
        mDieBieMS->commands()->sendTerminalCmd("help");
    }
}
