/* -*- mode: c++; c-basic-offset:4 -*-
    utils/path-helper.cpp

    This file is part of Kleopatra, the KDE keymanager
    SPDX-FileCopyrightText: 2009 Klarälvdalens Datakonsult AB

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

#include <config-kleopatra.h>

#include "path-helper.h"

#include <Libkleo/Stl_Util>

#include <Libkleo/KleoException>

#include "kleopatra_debug.h"
#include <KLocalizedString>

#include <QStandardPaths>
#include <QString>
#include <QStorageInfo>
#include <QFileInfo>
#include <QDir>

#include <algorithm>

using namespace Kleo;

static QString commonPrefix(const QString &s1, const QString &s2)
{
    return QString(s1.data(), std::mismatch(s1.data(), s1.data() + std::min(s1.size(), s2.size()), s2.data()).first - s1.data());
}

static QString longestCommonPrefix(const QStringList &sl)
{
    if (sl.empty()) {
        return QString();
    }
    QString result = sl.front();
    for (const QString &s : sl) {
        result = commonPrefix(s, result);
    }
    return result;
}

QString Kleo::heuristicBaseDirectory(const QStringList &fileNames)
{
    QStringList dirs;
    for (const QString &fileName : fileNames) {
        dirs.push_back(QFileInfo(fileName).path() + QLatin1Char('/'));
    }
    qCDebug(KLEOPATRA_LOG) << "dirs" << dirs;
    const QString candidate = longestCommonPrefix(dirs);
    /* Special case handling for Outlook and KMail attachment temporary path.
     * This is otherwise something like:
     * c:\users\username\AppData\Local\Microsoft\Windows\INetCache\
     *      Content.Outlook\ADSDFG9\foo.txt
     *
     * For KMail it is usually /tmp/messageviewer/foo
     *
     * Both are paths that are unlikely to be the target path to save the
     * decrypted attachment.
     *
     * This is very common when encrypted attachments are opened
     * within Outlook or KMail.
     */
    if (candidate.contains(QStringLiteral("Content.Outlook")) ||
        candidate.contains(QStringLiteral("messageviewer"))) {
        return QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    }
    const int idx = candidate.lastIndexOf(QLatin1Char('/'));
    return candidate.left(idx);
}

QStringList Kleo::makeRelativeTo(const QString &base, const QStringList &fileNames)
{

    if (base.isEmpty()) {
        return fileNames;
    } else {
        return makeRelativeTo(QDir(base), fileNames);
    }

}

QStringList Kleo::makeRelativeTo(const QDir &baseDir, const QStringList &fileNames)
{
    QStringList rv;
    rv.reserve(fileNames.size());
    std::transform(fileNames.cbegin(), fileNames.cend(),
                   std::back_inserter(rv),
                   [&baseDir](const QString &file) {
                       return baseDir.relativeFilePath(file);
                   });
    return rv;
}

QString Kleo::stripSuffix(const QString &fileName)
{
    const QFileInfo fi(fileName);
    return fi.dir().filePath(fi.completeBaseName());
}
