/*****************************************************************************
 * $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 "FileFieldEditor.h"

#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QFileDialog>
#include <QApplication>
#include <QImageReader>

// -------------------- Constructor --------------------
FileFieldEditor::FileFieldEditor(CamiTKExtensionModelPresenter* presenter, VariantDataModel& dataModel, const QString& name, const QString& description) : FieldEditor(presenter, dataModel, name, description) {
    filter = getDefaultImageFilter();
    // path is just declared → null string
}

// -------------------- getWidget --------------------
QWidget* FileFieldEditor::getWidget() {
    if (myWidget == nullptr) {
        QWidget* fileFieldEditorWidget = new QWidget();
        lineEdit = new QLineEdit();
        lineEdit->setReadOnly(true); // disable typing directly in the line edit

        QPushButton* selectFileButton = new QPushButton("Browse");
        connect(selectFileButton, &QPushButton::clicked, this, &FileFieldEditor::chooseFile);

        QHBoxLayout* layout = new QHBoxLayout(fileFieldEditorWidget);
        layout->addWidget(lineEdit);
        layout->addWidget(selectFileButton);

        myWidget = fileFieldEditorWidget;
    }
    return myWidget;
}

// -------------------- chooseFile --------------------
void FileFieldEditor::chooseFile() {
    QString fullFileName = QFileDialog::getOpenFileName(myWidget, "Choose File", "", filter);
    if (!fullFileName.isEmpty()) {
        lineEdit->setText(fullFileName);
        // if path is given copy to path and update the datamodel
        if (!path.isNull()) {
            QString fileName = QFileInfo(fullFileName).fileName();
            QString copyFileName = path + "/" + fileName;
            // Remove the file if exists locally
            if (QFile(copyFileName).exists()) {
                QFile::remove(copyFileName);
            }

            // copy the new version
            if (QFile::copy(fullFileName, copyFileName)) {
                // preserve the modification date of the copied file
                QDateTime modificationDate = QFileInfo(fullFileName).lastModified();
                QFile destinationFile(copyFileName);
                if (destinationFile.open(QIODevice::ReadOnly)) {
                    // to use setFileTime the file must be opened (see documentation)
                    destinationFile.setFileTime(modificationDate, QFileDevice::FileModificationTime);
                    destinationFile.close();

                    // modify the model using just the file name  (as it is copied now)
                    dataModel = fileName;
                    presenter->modelUpdated();
                }
            }
        }
        else {
            // modify the model using the full file name
            dataModel = fullFileName;
            presenter->modelUpdated();
        }
    }
}

// -------------------- setFilter --------------------
void FileFieldEditor::setFilter(QString filter) {
    this->filter = filter;
}

// -------------------- copyToPath --------------------
void FileFieldEditor::copyToPath(QString path) {
    this->path = path;
}

// -------------------- getDefaultImageFilter --------------------
QString FileFieldEditor::getDefaultImageFilter() {
    QString defaultFilter = QApplication::translate("IconSelector", "All Pixmaps (*.");
    auto supportedImageFormats = QImageReader::supportedImageFormats();
    QStringList allFilters;
    for (auto imageFormat : supportedImageFormats) {
        allFilters.append(QString::fromUtf8(imageFormat.toLower()));
    }
    // add "jpg"
    if (allFilters.contains("jpeg")) {
        allFilters.append("jpg");
    }
    defaultFilter += allFilters.join(" *.");
    defaultFilter += ")";
    return defaultFilter;
}
