src/EditProfileMash.cpp

Sun, 12 Feb 2023 13:58:36 +0100

author
Michiel Broek <mbroek@mbse.eu>
date
Sun, 12 Feb 2023 13:58:36 +0100
changeset 494
49ac23d25f61
parent 385
09af9f46518f
permissions
-rw-r--r--

In monitor iSpindel: in the chart calculate the ranges, do't let the toolkit do that. Save the path for chart image download in the user settings. In the tooltip for the battery voltage line, also show the remaining battery capacity. In the monitor window show the battery capacity digit instead of allways 0. Updated the translations.

/**
 * EditProfileMash.cpp is part of bmsapp.
 *
 * bmsapp is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * bmsapp is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "EditProfileMash.h"
#include "../ui/ui_EditProfileMash.h"
#include "MainWindow.h"


EditProfileMash::EditProfileMash(int id, QWidget *parent) : QDialog(parent), ui(new Ui::EditProfileMash)
{
    QSqlQuery query;

    qDebug() << "EditProfileMash record:" << id;
    ui->setupUi(this);
    this->recno = id;

    if (id >= 0) {
        query.prepare("SELECT * FROM profile_mash WHERE record = :recno");
        query.bindValue(":recno", id);
        query.exec();
        query.next();

        ui->nameEdit->setText(query.value(1).toString());
        ui->notesEdit->setPlainText(query.value(2).toString());
	QJsonParseError parseError;
        const auto& json = query.value(3).toString();

        if (!json.trimmed().isEmpty()) {
            const auto& formattedJson = QString("%1").arg(json);
            this->steps = QJsonDocument::fromJson(formattedJson.toUtf8(),  &parseError);

            if (parseError.error != QJsonParseError::NoError)
                qDebug() << "Parse error: " << parseError.errorString() << "at" << parseError.offset ;
	}

    } else {
        /* Set some defaults */
	const auto& formattedJson = QString("[]");
	this->steps = QJsonDocument::fromJson(formattedJson.toUtf8());
    }

    connect(ui->nameEdit, &QLineEdit::textChanged, this, &EditProfileMash::is_changed);
    connect(ui->notesEdit, SIGNAL(textChanged()), this, SLOT(is_changed()));
    connect(ui->stepsTable, SIGNAL(cellChanged(int, int)), this, SLOT(cell_Changed(int, int)));

    ui->saveButton->setEnabled(false);
    ui->deleteButton->setEnabled((id >= 0) ? true:false);

    emit refreshTable();

    WindowTitle();
}


void EditProfileMash::refreshTable()
{
    QString w;
    QWidget* pWidget;
    QHBoxLayout* pLayout;
    double  d;
    int	total = 0;

//    qDebug() << "refreshTable" << this->steps << this->steps.isArray() << this->steps.array().size() ;
    /* During filling the table turn off the cellChanged signal because every cell that is filled
     * triggers the cellChanged signal. The QTableWidget has no better signal to use. */
    this->ignoreChanges = true;

    const QStringList labels({tr("Step name"), tr("Type"), tr("Start °C"), tr("End °C"), tr("Rest time"), tr("Ramp time"), tr("Button")});
    ui->stepsTable->setColumnCount(7);
    ui->stepsTable->setColumnWidth(0, 250);	/* Step name	*/
    ui->stepsTable->setColumnWidth(1, 150);	/* Step type	*/
    ui->stepsTable->setColumnWidth(2,  75);	/* Start temp	*/
    ui->stepsTable->setColumnWidth(3,  75);	/* End temp	*/
    ui->stepsTable->setColumnWidth(4,  75);	/* Step time	*/
    ui->stepsTable->setColumnWidth(5,  75);	/* Ramp time	*/
    ui->stepsTable->setColumnWidth(6,  80);	/* Button	*/
    ui->stepsTable->setHorizontalHeaderLabels(labels);
    ui->stepsTable->verticalHeader()->hide();
    ui->stepsTable->setRowCount(this->steps.array().size());

    if (this->steps.isArray()) {
	for (int i = 0; i < this->steps.array().size(); i++) {
	    QJsonObject obj = this->steps.array().at(i).toObject();

	    ui->stepsTable->setItem(i, 0, new QTableWidgetItem(obj["step_name"].toString()));

	    /* Adding step_type 0, 1 or 2 as combobox. */
	    QComboBox* myComboBox = new QComboBox();
	    myComboBox->addItem(tr("Infusion"));
	    myComboBox->addItem(tr("Temperature"));
	    myComboBox->addItem(tr("Decoction"));
	    ui->stepsTable->setCellWidget(i, 1, myComboBox);
	    if (obj["step_type"].isString())
		d = QString(obj["step_type"].toString()).toDouble();
	    else
		d = obj["step_type"].toDouble();
	    myComboBox->setCurrentIndex((int)d);
	    connect<void(QComboBox::*)(int)>(myComboBox, &QComboBox::currentIndexChanged, this, &EditProfileMash::combo_Changed);

	    /* Numbers can be double quoted or not, the old application could do this wrong. */
	    if (obj["step_temp"].isString())
		d = QString(obj["step_temp"].toString()).toDouble();
	    else
		d = obj["step_temp"].toDouble();
	    w = QString("%1").arg(d, 2, 'f', 1, '0');
	    QTableWidgetItem *item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
	    ui->stepsTable->setItem(i, 2, item);

	    if (obj["end_temp"].isString())
                d = QString(obj["end_temp"].toString()).toDouble();
            else
                d = obj["end_temp"].toDouble();
            w = QString("%1").arg(d, 2, 'f', 1, '0');
            item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
            ui->stepsTable->setItem(i, 3, item);

	    if (obj["step_time"].isString())
                d = QString(obj["step_time"].toString()).toDouble();
            else
                d = obj["step_time"].toDouble();
            w = QString("%1").arg(d, 1, 'f', 0, '0');
            item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
            ui->stepsTable->setItem(i, 4, item);
	    total += (int)d;

	    if (obj["ramp_time"].isString())
                d = QString(obj["ramp_time"].toString()).toDouble();
            else
                d = obj["ramp_time"].toDouble();
            w = QString("%1").arg(d, 1, 'f', 0, '0');
            item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
            ui->stepsTable->setItem(i, 5, item);
	    if (i > 0)
		total += (int)d;

	    /* Add the Delete row button */
            pWidget = new QWidget();
            QPushButton* btn_edit = new QPushButton();
            btn_edit->setObjectName(QString("%1").arg(i));  /* Send row with the button */
            btn_edit->setText(tr("Delete"));
            connect(btn_edit, SIGNAL(clicked()), this, SLOT(on_deleteRow_clicked()));
            pLayout = new QHBoxLayout(pWidget);
            pLayout->addWidget(btn_edit);
            pLayout->setContentsMargins(5, 0, 5, 0);
            pWidget->setLayout(pLayout);
            ui->stepsTable->setCellWidget(i, 6, pWidget);
	}
    }

    /* Show the calculated total mash time. */
    ui->totalEdit->setText(QString("%1:%2").arg(total / 60).arg(total % 60, 2, 'f', 0, '0'));
    this->ignoreChanges = false;
}


EditProfileMash::~EditProfileMash()
{
    delete ui;
    emit entry_changed();
}


/*
 * Window header, mark any change with '**'
 */
void EditProfileMash::WindowTitle()
{
    QString txt;

    if (this->recno < 0) {
	txt = QString(tr("BMSapp - Add new mash profile"));
    } else {
	txt = QString(tr("BMSapp - Edit mash profile %1").arg(this->recno));
    }

    if (this->textIsChanged) {
	txt.append((QString(" **")));
    }
    setWindowTitle(txt);
}


void EditProfileMash::on_saveButton_clicked()
{
    QSqlQuery query;

    /* If there are errors in the form, show a message and do "return;" */
    if (ui->nameEdit->text().length() < 2) {
	QMessageBox::warning(this, tr("Edit Mash"), tr("Name empty or too short."));
	return;
    }

    if (this->textIsChanged) {
    	if (this->recno == -1) {
    	    query.prepare("INSERT INTO profile_mash SET name=:name, notes=:notes, steps=:steps, uuid=:uuid");
    	} else {
	    query.prepare("UPDATE profile_mash SET name=:name, notes=:notes, steps=:steps WHERE record=:recno");
    	}
	query.bindValue(":name", ui->nameEdit->text());
	query.bindValue(":notes", ui->notesEdit->toPlainText());
	query.bindValue(":steps", this->steps.toJson(QJsonDocument::Compact));

	if (this->recno == -1) {
	    query.bindValue(":uuid", QUuid::createUuid().toString().mid(1, 36));
	} else {
	    query.bindValue(":recno", this->recno);
	}
	query.exec();
	if (query.lastError().isValid()) {
	    qWarning() << "EditProfileMash" << query.lastError();
	    QMessageBox::warning(this, tr("Database error"),
                        tr("MySQL error: %1\n%2\n%3")
                        .arg(query.lastError().nativeErrorCode())
                        .arg(query.lastError().driverText())
                        .arg(query.lastError().databaseText()));
	} else {
	    qDebug() << "EditProfileMash Saved";
	}
    }

    ui->saveButton->setEnabled(false);
    this->textIsChanged = false;
    WindowTitle();
}


void EditProfileMash::on_cloneButton_clicked()
{
    QSqlQuery query;

    query.prepare("INSERT INTO profile_mash SET name=:name, notes=:notes, steps=:steps, uuid=:uuid");
    query.bindValue(":name", ui->nameEdit->text() + " [copy]");
    query.bindValue(":notes", ui->notesEdit->toPlainText());
    query.bindValue(":steps", this->steps.toJson(QJsonDocument::Compact));
    query.bindValue(":uuid", QUuid::createUuid().toString().mid(1, 36));

    query.exec();
    if (query.lastError().isValid()) {
	qWarning() << "EditProfileMash" << query.lastError();
	QMessageBox::warning(this, tr("Database error"),
                        tr("MySQL error: %1\n%2\n%3")
                        .arg(query.lastError().nativeErrorCode())
                        .arg(query.lastError().driverText())
                        .arg(query.lastError().databaseText()));
    } else {
	qDebug() << "EditProfileMash Saved";
    }
}


void EditProfileMash::on_deleteButton_clicked()
{
    QSqlQuery query;

    int rc = QMessageBox::warning(this, tr("Delete mash profile"), tr("Delete %1").arg(ui->nameEdit->text()),
                    QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    if (rc == QMessageBox::No)
        return;

    query.prepare("DELETE FROM profile_mash WHERE record = :recno");
    query.bindValue(":recno", this->recno);
    query.exec();
    if (query.lastError().isValid()) {
	qWarning() << "EditProfileMash" << query.lastError();
	QMessageBox::warning(this, tr("Database error"),
                        tr("MySQL error: %1\n%2\n%3")
                        .arg(query.lastError().nativeErrorCode())
                        .arg(query.lastError().driverText())
                        .arg(query.lastError().databaseText()));
    } else {
	qDebug() << "EditProfileMash Deleted" << this->recno;
    }

    this->close();
    this->setResult(1);
}


void EditProfileMash::is_changed()
{
    ui->saveButton->setEnabled(true);
    ui->deleteButton->setEnabled((this->recno >= 0) ? true:false);
    this->textIsChanged = true;
    WindowTitle();
}


/*
 * Rebuild the json string from the table contents.
 */
void EditProfileMash::make_Json()
{
    QTableWidgetItem *item;
    QJsonArray array;

    ui->stepsTable->sortItems(2, Qt::AscendingOrder);   // Sort on temperature.

    for (int i = 0; i < ui->stepsTable->rowCount(); i++) {

	QJsonObject obj;
	item = ui->stepsTable->item(i, 0);
	obj.insert("step_name", item->text());
	QWidget *widget = ui->stepsTable->cellWidget(i, 1);
        obj.insert("step_type", static_cast<QComboBox*>(widget)->currentIndex() );
	item = ui->stepsTable->item(i, 2);
	obj.insert("step_temp", item->text().toDouble());
	item = ui->stepsTable->item(i, 3);
        obj.insert("end_temp", item->text().toDouble());
	item = ui->stepsTable->item(i, 4);
        obj.insert("step_time", item->text().toInt());
	item = ui->stepsTable->item(i, 5);
        obj.insert("ramp_time", item->text().toInt());
//	qDebug() << "make_Json" << i << obj;
	array.append(obj);	/* Append this object */
    }

//    qDebug() << array;
    /* Copy to the global array and refresh */
    this->steps.setArray(array);
    is_changed();
    emit refreshTable();
}


void EditProfileMash::cell_Changed(int nRow, int nCol)
{
    if (this->ignoreChanges)
	return;

    qDebug() << "Cell at row " + QString::number(nRow) + " column " + QString::number(nCol) + " was changed.";

    // TODO: some checks and auto fixes.
    make_Json();
}


void EditProfileMash::combo_Changed()
{
    make_Json();
}


void EditProfileMash::on_addButton_clicked()
{
    int total = ui->stepsTable->rowCount();
    QWidget* pWidget;
    QHBoxLayout* pLayout;

    qDebug() << "Add row" << total;
    this->ignoreChanges = true;

    ui->stepsTable->insertRow(total);
    ui->stepsTable->setItem(total, 0, new QTableWidgetItem(QString("new row %1").arg(total)));
    QComboBox* myComboBox = new QComboBox();
    myComboBox->addItem(tr("Infusion"));
    myComboBox->addItem(tr("Temperature"));
    myComboBox->addItem(tr("Decoction"));
    myComboBox->setCurrentIndex(0);
    ui->stepsTable->setCellWidget(total, 1, myComboBox);
    ui->stepsTable->setItem(total, 2, new QTableWidgetItem(QString("65.0")));
    ui->stepsTable->setItem(total, 3, new QTableWidgetItem(QString("65.0")));
    ui->stepsTable->setItem(total, 4, new QTableWidgetItem(QString("20")));
    ui->stepsTable->setItem(total, 5, new QTableWidgetItem(QString("10")));
    pWidget = new QWidget();
    QPushButton* btn_edit = new QPushButton();
    btn_edit->setObjectName(QString("%1").arg(total));  /* Send row with the button */
    btn_edit->setText(tr("Delete"));
    connect(btn_edit, SIGNAL(clicked()), this, SLOT(on_deleteRow_clicked()));
    pLayout = new QHBoxLayout(pWidget);
    pLayout->addWidget(btn_edit);
    pLayout->setContentsMargins(5, 0, 5, 0);
    pWidget->setLayout(pLayout);
    ui->stepsTable->setCellWidget(total, 6, pWidget);

    this->ignoreChanges = false;
    make_Json();
}


void EditProfileMash::on_deleteRow_clicked()
{
    QPushButton *pb = qobject_cast<QPushButton *>(QObject::sender());
    int row = pb->objectName().toInt();
    qDebug() << "Delete row" << row;
    ui->stepsTable->removeRow(row);
    make_Json();
}


void EditProfileMash::on_quitButton_clicked()
{
    if (this->textIsChanged) {
	int rc = QMessageBox::warning(this, tr("Mash changed"), tr("This mash profile has been modified. Save changes?"),
                                QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save);
        switch (rc) {
            case QMessageBox::Save:
                        on_saveButton_clicked();
                        break;  /* Saved and then Quit */
            case QMessageBox::Discard:
                        break;  /* Quit without Save */
            case QMessageBox::Cancel:
                        return; /* Return to the editor page */
        }
    }

    this->close();
    this->setResult(1);
}

mercurial