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

#pragma once

#include <memory>

#include <QObject>

#include "jsdialogrequest.h"

namespace Aurora {
namespace WebView {

class BeforeUnloadDialogRequestInternal;

/**
 * @class BeforeUnloadDialogRequest
 * @brief Represents JavaScript onbeforeunload dialog request
 * 
 * When you try leaving a webpage that has unsaved changes
 * (and webpage itself handles such cases with `window.onbeforeunload` event handler),
 * this dialog appears. You can then confirm and leave the page, or
 * cancel navigation.
 * 
 */
class BeforeUnloadDialogRequest : public JSDialogRequest
{
    Q_GADGET

    /// URL of the web page that called the function
    Q_PROPERTY(QString sourceUrl READ sourceUrl)
    /// message from the function that triggered the dialog
    Q_PROPERTY(QString message READ message)
    /// returns true if the request is valid, do not use otherwise
    Q_PROPERTY(bool isValid READ isValid)
    /// isReload shows whether the dialog was activated by reloading the page
    ///
    /// True if the dialog was activated by reloading the page
    ///
    /// False if the dialog was activated by closing a web page or navigating
    /// to another web page
    Q_PROPERTY(bool isReload READ isReload)
public:
    /**
     * @brief Constructs a new BeforeUnloadDialogRequest object
     * This constructor is declared to register
     * this class in QML
     */
    BeforeUnloadDialogRequest();
    BeforeUnloadDialogRequest(const BeforeUnloadDialogRequest &other) = default;
    /**
     * @brief Destroys the BeforeUnloadDialogRequest object
     */
    ~BeforeUnloadDialogRequest() = default;

    bool isReload() const;

    /**
     * @brief Used to exit from onbeforeunload dialog and leave/reload the page
     */
    Q_INVOKABLE virtual void leavePage();

    /**
     * @brief Used to exit from onbeforeunload dialog and stay on the page
     */
    Q_INVOKABLE virtual void cancel();

    bool isValid() const override;

private:
    BeforeUnloadDialogRequest(
        QString messageText,
        std::shared_ptr<BeforeUnloadDialogRequestInternal> dialogRequestInternal);

    std::shared_ptr<BeforeUnloadDialogRequestInternal> m_d;

    friend class BeforeUnloadDialogRequestInternal;
};

} // namespace WebView
} // namespace Aurora

Q_DECLARE_METATYPE(Aurora::WebView::BeforeUnloadDialogRequest)
