/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK 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 Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include "FieldEditor.h"

#include <QPushButton>
#include <QStyle>
#include <QMessageBox>

// -------------------- Constructor --------------------
FieldEditor::FieldEditor(CamiTKExtensionModelPresenter* presenter, VariantDataModel& dataModel, const QString& name, const QString& description) : dataModel(dataModel) {
    this->presenter = presenter;
    this->name = name;
    this->description = description;
    myGridLayout = nullptr;
    rowLabel = nullptr;
    myWidget = nullptr;
}

// -------------------- Destructor --------------------
FieldEditor::~FieldEditor() {
    delete myWidget;
}

// -------------------- appendRowTo --------------------
void FieldEditor::appendRowTo(QGridLayout* layout, bool canBeDeleted) {
    myGridLayout = layout;
    int row = myGridLayout->rowCount(); // append at this row

    QStringList words = name.split(" ", Qt::SkipEmptyParts);
    QStringList capitalizedWords;
    for (const QString& word : words) {
        if (!word.left(1).isUpper()) {
            capitalizedWords << word.left(1).toUpper() + word.mid(1).toLower();
        }
        else {
            // word starts with an upper case letter, just copy it (e.g. ITK → ITK, CamiTK → CamiTK)
            capitalizedWords << word;
        }
    }
    QString labelString = capitalizedWords.join(" ");

    rowLabel = new QLabel(labelString);

    QPushButton* deleteButton = nullptr;
    if (canBeDeleted) {
        QWidget* deleteWidget = new QWidget();
        QHBoxLayout* deleteLayout = new QHBoxLayout(deleteWidget);
        deleteLayout->addWidget(rowLabel);

        deleteButton = new QPushButton(getWidget()->style()->standardIcon(QStyle::SP_TitleBarCloseButton), "");
        deleteButton->setFixedHeight(deleteButton->fontMetrics().height());
        deleteButton->setFixedWidth(deleteButton->fontMetrics().height());
        deleteButton->setStyleSheet("background-color: none; border: none; text-align: right;");
        deleteButton->setToolTip("Remove '" + labelString + "' (cannot be undone)");
        deleteLayout->addWidget(deleteButton);
        myGridLayout->addWidget(deleteWidget, row, 0);
        // add signal to hide the line and item in the model
        connect(deleteButton, &QPushButton::clicked, this, &FieldEditor::deleteButtonClicked);
    }
    else {
        myGridLayout->addWidget(rowLabel, row, 0);
    }

    getWidget()->setWhatsThis(description);
    getWidget()->setToolTip(description);
    myGridLayout->addWidget(getWidget(), row, 1);
}

// -------------------- setEnabled --------------------
void FieldEditor::setEnabled(bool isEnabled) {
    if (myWidget) {
        myWidget->setEnabled(isEnabled);
    }
    if (rowLabel) {
        rowLabel->setEnabled(isEnabled);
    }
}

// -------------------- deleteButtonClicked --------------------
void FieldEditor::deleteButtonClicked() {
    QMessageBox::StandardButton reply = QMessageBox::warning(myWidget, "Remove '" + rowLabel->text() + "'?",
                                        tr("Warning: removing '%1' cannot be undone. Are you sure you want to proceed?").arg(rowLabel->text()),
                                        QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        // remove the UI
        int index = myGridLayout->indexOf(myWidget);
        int row, column, rowSpan, columnSpan;
        myGridLayout->getItemPosition(index, &row, &column, &rowSpan, &columnSpan);
        // Iterate over all items in the row
        for (int i = 0; i < myGridLayout->columnCount(); ++i) {
            QLayoutItem* item = myGridLayout->itemAtPosition(row, i);
            if (item != nullptr) {
                // Remove the widget from the layout
                myGridLayout->removeItem(item);
                // Delete the widget
                delete item->widget();
                // Delete the layout item
                delete item;
            }
        }

        // remove the model (set value to invalid QVariant)
        dataModel.remove();

        presenter->emitShowMessage("'" + name + "' deleted.");
        presenter->modelUpdated();
    }
}
