/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: https://neueland.iserlohn-fortress.net/smolbote.hg
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "webprofile.h"
#include <QFileInfo>
#include <QSettings>
#include <QWebEngineCookieStore>
#include <QWebEngineSettings>

WebProfile *WebProfile::profile = nullptr;

WebProfile* loadProfile(const QString &name, const QHash<QString, QString> &defaults, const QString &path, QObject *parent)
{
    WebProfile *profile = nullptr;
#ifdef QT_DEBUG
    qDebug("+ Reading config for profile '%s': %s", qUtf8Printable(name), qUtf8Printable(path));
#endif
    QSettings config(path, QSettings::IniFormat);

    if(name.isEmpty()) {
        // a default otr profile
        profile = new WebProfile(QObject::tr("Off-the-record"), path, parent);

    } else if(config.value("otr").toBool()) {
        // a named otr profile
        profile = new WebProfile(config.value("name", name).toString(), path, parent);

    } else {
        // a named profile
        profile = new WebProfile(name, config.value("name", name).toString(), path, parent);
    }

    Q_CHECK_PTR(profile);

    profile->setSearch(config.value("search", defaults.value("profile.search")).toString());
    profile->setHomepage(config.value("homepage", defaults.value("profile.homepage")).toUrl());
    profile->setNewtab(config.value("newtab", defaults.value("profile.newtab")).toUrl());

    config.beginGroup("properties");
    {
        const auto keys = config.childKeys();
        for(const QString &key : keys) {
#ifdef QT_DEBUG
            qDebug("- set property %s to %s", qUtf8Printable(key), qUtf8Printable(config.value(key).toString()));
#endif
            profile->setProperty(qUtf8Printable(key), config.value(key));
        }
    }
    config.endGroup(); // properties

    config.beginGroup("attributes");
    {
        const auto keys = config.childKeys();
        auto *settings = profile->settings();
        for(const QString &key : keys) {
#ifdef QT_DEBUG
            qDebug("- set attribute %s to %s", qUtf8Printable(key), qUtf8Printable(config.value(key).toString()));
#endif
            auto attribute = static_cast<QWebEngineSettings::WebAttribute>(key.toInt());
            settings->setAttribute(attribute, config.value(key).toBool());
        }
    }
    config.endGroup();

    return profile;
}

WebProfile::WebProfile(const QString &name, const QString &configPath, QObject *parent)
    : QWebEngineProfile(parent)
{
    m_name = name;
    m_configPath = configPath;

#ifdef QT_DEBUG
    qDebug("Creating otr profile %s", qUtf8Printable(m_name));
#endif

    connect(this->cookieStore(), &QWebEngineCookieStore::cookieAdded, this, [this](const QNetworkCookie &cookie) {
        m_cookies.append(cookie);
    });
    connect(this->cookieStore(), &QWebEngineCookieStore::cookieRemoved, this, [this](const QNetworkCookie &cookie) {
        m_cookies.removeAll(cookie);
    });
}

WebProfile::WebProfile(const QString &storageName, const QString &name, const QString &configPath, QObject *parent)
    : QWebEngineProfile(storageName, parent)
{
    m_name = name;
    m_configPath = configPath;

#ifdef QT_DEBUG
    qDebug("Creating profile %s", qUtf8Printable(m_name));
#endif

    connect(this->cookieStore(), &QWebEngineCookieStore::cookieAdded, this, [this](const QNetworkCookie &cookie) {
        m_cookies.append(cookie);
    });
    connect(this->cookieStore(), &QWebEngineCookieStore::cookieRemoved, this, [this](const QNetworkCookie &cookie) {
        m_cookies.removeAll(cookie);
    });
}

QString WebProfile::search() const
{
    return m_search;
}

void WebProfile::setSearch(const QString &url)
{
    m_search = url;
    emit searchChanged(m_search);
}

QUrl WebProfile::homepage() const
{
    return m_homepage;
}

void WebProfile::setHomepage(const QUrl &url)
{
    m_homepage = url;
    emit homepageChanged(m_homepage);
}

QUrl WebProfile::newtab() const
{
    return m_newtab;
}

void WebProfile::setNewtab(const QUrl &url)
{
    m_newtab = url;
    emit newtabChanged(m_newtab);
}

void WebProfile::setCachePath(const QString &path)
{
    QWebEngineProfile::setCachePath(path);
    emit cachePathChanged(QWebEngineProfile::cachePath());
}

void WebProfile::setPersistentStoragePath(const QString &path)
{
    QWebEngineProfile::setPersistentStoragePath(path);
    emit persistentStoragePathChanged(QWebEngineProfile::persistentStoragePath());
}

void WebProfile::setHttpAcceptLanguage(const QString &httpAcceptLanguage)
{
    QWebEngineProfile::setHttpAcceptLanguage(httpAcceptLanguage);
    emit httpAcceptLanguageChanged(QWebEngineProfile::httpAcceptLanguage());
}

void WebProfile::setHttpCacheMaximumSize(int maxSize)
{
    QWebEngineProfile::setHttpCacheMaximumSize(maxSize);
    emit httpCacheMaximumSizeChanged(QWebEngineProfile::httpCacheMaximumSize());
}

void WebProfile::setHttpUserAgent(const QString &userAgent)
{
    QWebEngineProfile::setHttpUserAgent(userAgent);
    emit httpUserAgentChanged(QWebEngineProfile::httpUserAgent());
}

void WebProfile::setSpellCheckEnabled(bool enable)
{
    QWebEngineProfile::setSpellCheckEnabled(enable);
    emit spellCheckEnabledChanged(QWebEngineProfile::isSpellCheckEnabled());
}