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

#include <Application.h>
#include <ExtensionManager.h>
#include <ImageComponent.h>
#include <ImageComponentExtension.h>
#include <MeshComponent.h>
#include <MeshComponentExtension.h>
#include <Log.h>

#include <QFileDialog>

using namespace camitk;


// --------------- constructor -------------------
SaveAsAction::SaveAsAction(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Save As");
    setEmbedded(false);
    setDescription(tr("Save the currently selected data under a different filename or format"));
    setComponentClassName("Component");
    setIcon(QPixmap(":/fileSaveAs"));

    // Setting classification family and tags
    setFamily("File");
    addTag(tr("Save As"));

    // add shortcuts
    getQAction()->setShortcut(QKeySequence::SaveAs);
    getQAction()->setShortcutContext(Qt::ApplicationShortcut);
}

// --------------- destructor -------------------
SaveAsAction::~SaveAsAction() {
    // do not delete the widget has it might have been used in the ActionViewer (i.e. the ownership might have been taken by the stacked widget)
}

// --------------- getWidget --------------
QWidget* SaveAsAction::getWidget() {
    return nullptr;
}

// --------------- apply -------------------
Action::ApplyStatus SaveAsAction::apply() {
    Component* comp = getTargets().last();
    if (!Application::isAlive(comp)) {
        CAMITK_ERROR("SaveAsAction was called to save an invalid Component");
        return ERROR;
    }

    Application::showStatusBarMessage(tr("Saving currently selected component under new filename or format..."));

    // Get the possible save as extension... (compatible formats)
    QStringList filterList;

    // first check if there is a filename
    QString compfileName = comp->getFileName();

    // check the extension
    QString extension = QFileInfo(compfileName).completeSuffix();

    // if no extension is found, look for the export of plugins which write directories
    if (!compfileName.isEmpty() && extension.isEmpty() && comp->isTopLevel()) {
        for (QString cpName : ExtensionManager::getDataDirectoryExtNames()) {
            const ComponentExtension* cp = ExtensionManager::getComponentExtension(cpName);
            filterList += cpName + cp->getFileExtensions().join(" ");
        }
    }

    // Select extension depending on the selected component:
    // - save as another image when it's an image
    // - save as another mesh when it's a mesh
    // - save as anything otherwise
    const ImageComponent* compAsImg  = dynamic_cast<const ImageComponent*>(comp);
    const MeshComponent*  compAsMesh = dynamic_cast<const MeshComponent*>(comp);

    for (ComponentExtension* compExt : ExtensionManager::getComponentExtensionsList()) {
        const ComponentExtension* selectedExt = nullptr;
        if (compAsImg) {
            if (dynamic_cast<const ImageComponentExtension*>(compExt)) {
                selectedExt = compExt;
            }
        }
        else if (compAsMesh) {
            if (dynamic_cast<const MeshComponentExtension*>(compExt)) {
                selectedExt = compExt;
            }
        }
        else {
            selectedExt = compExt;
        }
        if (selectedExt != nullptr) {
            for (QString ext : compExt->getFileExtensions()) {
                filterList += compExt->getName() + " (." + ext + ") (" + "*." + ext + " " + ")";
            }
        }
    }

    // suggest a new name (code snippet from KSnapObject::autoincFilename(), from the ksnapshot project)
    // Extract the filename from the path
    QString suggestedName = QFileInfo(compfileName).fileName();

    // use the top level component name if there is no file name
    if (suggestedName.isEmpty()) {
        suggestedName = comp->getName();
    }
    else {
        // If the name contains a number then increment it
        QRegularExpression numSearch("(^|[^\\d])(\\d+)");   // we want to match as far left as possible, and when the number is at the start of the name
        QRegularExpressionMatch match = numSearch.match(suggestedName);

        // Does it have a number?
        int start = suggestedName.lastIndexOf(numSearch);

        if (start != -1) {
            // It has a number, increment it
            QRegularExpressionMatch match = numSearch.match(suggestedName, start);
            QString numAsStr = match.captured(2); // we are only interested in the second group
            QString number = QString::number(numAsStr.toInt() + 1);
            number = number.rightJustified(numAsStr.length(), '0');
            suggestedName.replace(match.capturedStart(2), numAsStr.length(), number);
        }
        else {
            // no number
            start = suggestedName.lastIndexOf('.');

            if (start != -1) {
                // has a . somewhere, e.g. it has an extension
                suggestedName.insert(start, '1');
            }
            else {
                // no extension, just tack it on to the end
                suggestedName += '1';
            }
        }
    }

    // filters
    QString filters = filterList.join(";;");

    // Guess the directory we want to save in
    QString directory;
    if (compfileName.isEmpty()) {
        directory = Application::getLastUsedDirectory().absolutePath();
    }
    else {
        directory = QFileInfo(compfileName).dir().canonicalPath();
    }

    // get the file name
    QString filename = QFileDialog::getSaveFileName(nullptr, tr("Save File As..."), directory + "/" + suggestedName, filters, nullptr, QFileDialog::HideNameFilterDetails);

    if (!filename.isEmpty()) {
        // rename the filename of the component and save
        comp->setFileName(filename);
        // save the file as the new name
        bool saveStatus = Application::save(comp);

        // reset name if there was a problem
        if (saveStatus) {
            return SUCCESS;
        }
        else {
            comp->setFileName(compfileName);
            CAMITK_WARNING(tr("Canceled. Action Aborted."))
            return ABORTED;
        }
    }
    else {
        Application::showStatusBarMessage(tr("Saving aborted"), 2000);
        // CCC Exception: just a trace message as the user voluntarily aborted the action
        CAMITK_TRACE(tr("A filename is required. Action aborted."))
        return ABORTED;
    }

}

