/*
   SPDX-FileCopyrightText: 2020-2026 Laurent Montel <montel@kde.org>

   SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "savefileutils.h"

#include "textaddonswidgets_debug.h"
#include <KLocalizedString>
#include <KMessageBox>
#include <KRecentDirs>

#include <QFileDialog>
#include <QMimeDatabase>
#include <QStandardPaths>
#include <QUrl>

#include <KFileWidget>
using namespace Qt::Literals::StringLiterals;
using namespace TextAddonsWidgets;
QString SaveFileUtils::querySaveFileName(QWidget *parent, const QString &title, const QUrl &fileToSave)
{
    QString fileClass;
    const QUrl startUrl = KFileWidget::getStartUrl(QUrl(u"kfiledialog:///saveattachment"_s), fileClass);
    const auto info = QFileInfo(fileToSave.path());
    auto fileName = fileToSave.fileName();
    if (fileToSave.isLocalFile() && info.exists() && info.suffix().isEmpty()) {
        // guess a proper file suffix if none is given
        [&]() {
            QFile file(info.absoluteFilePath());
            if (!file.open(QIODevice::ReadOnly)) {
                return;
            }
            const QMimeDatabase mimeDb;
            const auto mime = mimeDb.mimeTypeForFileNameAndData(fileName, &file);
            if (!mime.isValid()) {
                return;
            }
            const auto suffix = mime.preferredSuffix();
            if (!suffix.isEmpty()) {
                fileName += u'.' + suffix;
            }
        }();
    }
    const QUrl localUrl = QUrl::fromLocalFile(startUrl.path() + u'/' + fileName);
    const QString fileStr = QFileDialog::getSaveFileName(parent, title, localUrl.path());

    if (!fileClass.isEmpty() && !fileStr.isEmpty()) {
        const QFileInfo fileInfo(fileStr);
        KRecentDirs::add(fileClass, fileInfo.absoluteDir().path());
    }
    return fileStr;
}

void SaveFileUtils::saveFile(QWidget *parentWidget, const QString &filePath, const QString &title)
{
    const auto file = SaveFileUtils::querySaveFileName(parentWidget, title, QUrl::fromLocalFile(filePath));
    if (file.isEmpty()) {
        return;
    }

    QFile sourceFile(filePath);
    if (!sourceFile.exists()) {
        KMessageBox::error(parentWidget, i18n("Source file no longer exists"), i18nc("@title:window", "Error saving file"));
        return;
    }

    QFile destFile(file);
    if (destFile.exists() && !destFile.remove()) {
        KMessageBox::error(parentWidget, i18n("Cannot overwrite existing file"), i18nc("@title:window", "Error saving file"));
        return;
    }

    if (!sourceFile.copy(file)) {
        KMessageBox::error(parentWidget, sourceFile.errorString(), i18nc("@title:window", "Error saving file"));
    }
}
