/*
 * SPDX-FileCopyrightText: Copyright 2024-2025 Open Mobile Platform LLC <community@omp.ru>
 * SPDX-License-Identifier: Proprietary
 */

#pragma once

#include "icookiemanager.h"

#include <memory>
#include <QObject>

class QQmlEngine;
class QJSEngine;

namespace Aurora {
namespace WebView {

class CookieManagerPrivate;

/**
 * @class CookieManager
 * @brief can be used to manage cookies.
 * 
 * CookieManager is a global singleton class that works with a regular WebViewItem.
 */
class CookieManager : public QObject
{
    Q_OBJECT
public:
    /**
     * @brief Default destructor
     */
    virtual ~CookieManager();
    /**
     * @brief returns instance of a global CookieManager
     */
    static QSharedPointer<CookieManager> GetInstance(
        QQmlEngine *qmlEngine = nullptr, QJSEngine *jsEngine = nullptr);

    /// Call to retrieve all existing cookies.
    ///
    /// @return true if cookies can be accessed, result comes with cookiesAvailable() signal
    Q_INVOKABLE bool retrieveAllCookies();

    /**
     * @brief Call to retrieve cookies for a specific URL.
     * 
     * @param url url (https://url.com)
     * @param includeHttpOnly pass true to also retrieve HTTP-only cookies
     * 
     * @return true if cookies can be accessed, result comes with cookiesAvailable() signal
     */
    Q_INVOKABLE bool retrieveUrlCookies(const QString &url, bool includeHttpOnly);
    /**
     * @brief Call to delete cookies.
     * 
     * @param url url (url.com)
     * @param cookieName specific cookie name
     * 
     * If both url and cookieName values are specified, all host and domain cookies matching
     * both will be deleted. If only url is specified, all host cookies (but not domain
     * cookies) irrespective of path will be deleted. If url is empty, all cookies for all
     * hosts and domains will be deleted.
     * 
     * @return true if cookies can be accessed, result comes with cookiesDeleted() signal
     * false if url is non-empty and invalid.
     */
    Q_INVOKABLE bool deleteCookies(const QString &url, const QString &cookieName);

    void notifyAllCookiesAvailable(QList<Cookie> cookies);
    void notifyUrlCookiesAvailable(QList<Cookie> cookies);
    void notifyCookiesDeleted(int count);

signals:
    /// emitted when a cookie retrieval result is available (for all cookies)
    void allCookiesAvailable(QVariantList cookies);
    /// emitted when a cookie retrieval result is available (for url cookies)
    void urlCookiesAvailable(QVariantList cookies);
    /// emitted on successful cookie deletion
    void cookiesDeleted(int count);

private:
    CookieManager();

    std::unique_ptr<CookieManagerPrivate> m_d;
};
} // namespace WebView
} // namespace Aurora
