// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
// Qt-Security score:significant

#include "qqmltoolingsettings_p.h"

#include <QtCore/qdebug.h>
#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qset.h>
#if QT_CONFIG(settings)
#include <QtCore/qsettings.h>
#endif
#include <QtCore/qstandardpaths.h>

using namespace Qt::StringLiterals;

void QQmlToolingSettings::addOption(const QString &name, QVariant defaultValue)
{
    if (defaultValue.isValid()) {
        m_values[name] = defaultValue;
    }
}

bool QQmlToolingSettings::read(const QString &settingsFilePath)
{
#if QT_CONFIG(settings)
    if (!QFileInfo::exists(settingsFilePath))
        return false;

    if (m_currentSettingsPath == settingsFilePath)
        return true;

    QSettings settings(settingsFilePath, QSettings::IniFormat);

    for (const QString &key : settings.allKeys())
        m_values[key] = settings.value(key).toString();

    m_currentSettingsPath = settingsFilePath;

    return true;
#else
    Q_UNUSED(settingsFilePath);
    return false;
#endif
}

bool QQmlToolingSettings::writeDefaults() const
{
#if QT_CONFIG(settings)
    const QString path = QFileInfo(u".%1.ini"_s.arg(m_toolName)).absoluteFilePath();

    QSettings settings(path, QSettings::IniFormat);
    for (auto it = m_values.constBegin(); it != m_values.constEnd(); ++it) {
        settings.setValue(it.key(), it.value().isNull() ? QString() : it.value());
    }

    settings.sync();

    if (settings.status() != QSettings::NoError) {
        qWarning() << "Failed to write default settings to" << path
                   << "Error:" << settings.status();
        return false;
    }

    qInfo() << "Wrote default settings to" << path;
    return true;
#else
    return false;
#endif
}

bool QQmlToolingSettings::search(const QString &path)
{
#if QT_CONFIG(settings)
    QFileInfo fileInfo(path);
    QDir dir(fileInfo.isDir() ? path : fileInfo.dir());

    QSet<QString> dirs;

    const QString settingsFileName = u".%1.ini"_s.arg(m_toolName);

    while (dir.exists() && dir.isReadable()) {
        const QString dirPath = dir.absolutePath();

        if (m_seenDirectories.contains(dirPath)) {
            const QString cachedIniPath = m_seenDirectories[dirPath];
            if (cachedIniPath.isEmpty())
                return false;

            return read(cachedIniPath);
        }

        dirs << dirPath;

        const QString iniFile = dir.absoluteFilePath(settingsFileName);

        if (read(iniFile)) {
            for (const QString &dir : std::as_const(dirs))
                m_seenDirectories[dir] = iniFile;
            return true;
        }

        if (!dir.cdUp())
            break;
    }

    // First try to locate settings file with the standard name
    QString iniFile =
            QStandardPaths::locate(QStandardPaths::GenericConfigLocation, settingsFileName);
    // If not found, try alternate name format
    if (iniFile.isEmpty()) {
        iniFile = QStandardPaths::locate(QStandardPaths::GenericConfigLocation,
                                         u"%1.ini"_s.arg(m_toolName));
    }

    // If a valid settings file was found, read it and update directory cache
    if (!iniFile.isEmpty() && read(iniFile)) {
        for (const QString &dir : std::as_const(dirs)) {
            m_seenDirectories[dir] = iniFile;
        }
        return true;
    }

    // No INI file found anywhere, record the failure so we won't have to traverse the entire
    // filesystem again
    for (const QString &dir : std::as_const(dirs))
        m_seenDirectories[dir] = QString();

#endif
    Q_UNUSED(path);
    return false;
}

QVariant QQmlToolingSettings::value(const QString &name) const
{
    return m_values.value(name);
}

QStringList QQmlToolingSettings::valueAsStringList(const QString &name) const
{
    return value(name).toString().split(QDir::listSeparator());
}

void QQmlToolingSettings::resolveRelativeImportPaths(const QString &filePath, QStringList *paths)
{
    // transform relative paths in absolute paths starting from filePath's directory
    const QDir fileDir = QFileInfo(filePath).absoluteDir();
    for (auto it = paths->begin(), end = paths->end(); it != end; ++it) {
        if (QFileInfo(*it).isAbsolute())
            continue;
        *it = QDir::cleanPath(fileDir.filePath(*it));
    }
}

QStringList QQmlToolingSettings::valueAsAbsolutePathList(const QString &name,
                                                         const QString &baseForRelativePaths) const
{
    QStringList paths = valueAsStringList(name);
    resolveRelativeImportPaths(baseForRelativePaths, &paths);
    return paths;
}

bool QQmlToolingSettings::isSet(const QString &name) const
{
    if (!m_values.contains(name))
        return false;

    QVariant variant = m_values[name];

    // Unset is encoded as an empty string
    return !(variant.canConvert(QMetaType(QMetaType::QString)) && variant.toString().isEmpty());
}
