/***********************************************************************
 * SPDX-FileCopyrightText: 2003-2004 Max Howell <max.howell@methylblue.com>
 * SPDX-FileCopyrightText: 2008-2009 Martin Sandsmark <martin.sandsmark@kde.org>
 * SPDX-FileCopyrightText: 2022 Harald Sitter <sitter@kde.org>
 *
 * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
 ***********************************************************************/

#include "Config.h"

#include <KConfig>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KSharedConfig>

#include <QDebug>
#include <QFileDialog>
#include <QFont>
#include <QQmlEngine>

#include "filelightsettings.h"

void Config::read()
{
    FilelightSettings config;

    scanAcrossMounts = config.scanAcrossMounts();
    scanRemoteMounts = config.scanRemoteMounts();
    showSmallFiles = config.showSmallFiles();
    showFoldersSidebar = config.showFoldersSidebar();
    contrast = config.contrast();
    scheme = (Filelight::MapScheme)config.scheme();
    skipList = config.skipList();

    Q_EMIT changed();
}

void Config::write() const
{
    FilelightSettings config;

    config.setScanAcrossMounts(scanAcrossMounts);
    config.setScanRemoteMounts(scanRemoteMounts);
    config.setShowSmallFiles(showSmallFiles);
    config.setShowFoldersSidebar(showFoldersSidebar);
    config.setContrast(contrast);
    config.setScheme((int)scheme); // TODO: make the enum belong to a qwidget,
    // and use magic macros to make it save this properly
    config.setSkipList(skipList);

    config.save();
}

Config *Config::instance()
{
    static Config self;
    return &self;
}

void Config::addFolder()
{
    const QString urlString = QFileDialog::getExistingDirectory(nullptr, i18n("Select path to ignore"), QDir::rootPath());
    const QUrl url = QUrl::fromLocalFile(urlString);

    // TODO error handling!
    // TODO wrong protocol handling!

    if (!url.isEmpty()) {
        const QString path = url.toLocalFile();

        if (!skipList.contains(path)) {
            skipList.append(path);
            Q_EMIT changed();
        } else {
            Q_EMIT addFolderFailed(i18n("Folder already ignored"));
        }
    }
}

void Config::removeFolder(const QString &url)
{
    qDebug() << url;
    skipList.removeAll(url);
    Q_EMIT changed();
}

Config *Config::create(QQmlEngine *qml, QJSEngine *js)
{
    auto config = Config::instance();
    QQmlEngine::setObjectOwnership(config, QQmlEngine::CppOwnership);
    return config;
}

Config::Config(QObject *parent)
    : QObject(parent)
{
}
