/****************************************************************************
**
** SPDX-FileCopyrightText: 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtFeedback module of the Qt Toolkit.
**
** SPDX-License-Identifier: LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KFQF-Accepted-GPL OR LicenseRef-Qt-Commercial
**
****************************************************************************/
#ifndef QFEEDBACKPLUGINSEARCH_H
#define QFEEDBACKPLUGINSEARCH_H

#include <QCoreApplication>
#include <QStringList>
#include <QDir>
#include <QDebug>

QT_BEGIN_NAMESPACE

inline QStringList getPluginPaths(const QString& plugintype)
{
    const bool showDebug = qEnvironmentVariableIntValue("QT_DEBUG_PLUGINS") > 0;

    const QStringList paths = QCoreApplication::libraryPaths();
    if (showDebug)
        qDebug() << "Plugin paths:" << paths;

    // Temp variable to avoid multiple identical paths
    // (we don't convert the list to set first, because that loses the order)
    QSet<QString> processed;

    /* The list of discovered plugins */
    QStringList plugins;

    /* Enumerate our plugin paths */
    for (const auto &path : paths) {
        if (processed.contains(path))
            continue;
        processed.insert(path);
        QDir pluginsDir(path);
        if (!pluginsDir.exists())
            continue;

#if defined(Q_OS_WIN)
        if (pluginsDir.dirName().toLower() == QLatin1String("debug") || pluginsDir.dirName().toLower() == QLatin1String("release"))
            pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
        if (pluginsDir.dirName() == QLatin1String("MacOS")) {
            pluginsDir.cdUp();
            pluginsDir.cdUp();
            pluginsDir.cdUp();
        }
#endif

        QString subdir(QStringLiteral("plugins/"));
        subdir += plugintype;
        if (pluginsDir.path().endsWith(QLatin1String("/plugins"))
            || pluginsDir.path().endsWith(QLatin1String("/plugins/")))
            subdir = plugintype;

        if (QDir(pluginsDir.filePath(subdir)).exists()) {
            pluginsDir.cd(subdir);
            const QStringList files = pluginsDir.entryList(QDir::Files);

            if (showDebug)
                qDebug() << "Looking for " << plugintype << " plugins in" << pluginsDir.path() << files;

            for (const auto &file : files) {
                plugins << pluginsDir.absoluteFilePath(file);
            }
        }
    }

  return  plugins;
}

QT_END_NAMESPACE

#endif
