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

#pragma once

#include "utils_global.h"

#include "filepath.h"

#include <QTextBrowser>
#include <QTextFragment>

QT_BEGIN_NAMESPACE
class QTextFrame;
QT_END_NAMESPACE

QT_BEGIN_NAMESPACE
class QNetworkAccessManager;
class QNetworkRequest;
class QPaintEvent;
class QShowEvent;
class QWheelEvent;
QT_END_NAMESPACE

namespace Utils {

class QtcButton;

class QTCREATOR_UTILS_EXPORT MarkdownBrowser : public QTextBrowser
{
    Q_OBJECT
public:
    using RequestHook = std::function<void (QNetworkRequest *)>;

    MarkdownBrowser(QWidget *parent = nullptr);

    void setMarkdown(const QString &markdown);
    QString toMarkdown() const;
    void setBasePath(const FilePath &filePath);
    void setAllowRemoteImages(bool allow);
    void setNetworkAccessManager(QNetworkAccessManager *nam);
    void setRequestHook(const RequestHook &hook);
    void setMaximumCacheSize(qsizetype maxSize);
    void setScale(qreal scale);
    qreal scale() const;
    void increaseZoom();
    void decreaseZoom();
    void resetZoom();

    QSize sizeHint() const override;
    QSize minimumSizeHint() const override;

    void setWheelZoomEnabled(bool enabled);
    bool isWheelZoomEnabled() const;
    void setMargins(const QMargins &margins);
    void setEnableCodeCopyButton(bool enable);
    void setShowRulersForHeadings(bool show);

protected:
    void wheelEvent(QWheelEvent *event) override;
    void changeEvent(QEvent *event) override;
    void showEvent(QShowEvent *event) override;
    void resizeEvent(QResizeEvent *event) override;
    void scrollContentsBy(int dx, int dy) override;
    void paintEvent(QPaintEvent *event) override;

    QMimeData *createMimeDataFromSelection() const override;

private:
    void showZoomIndicator();
    void handleAnchorClicked(const QUrl &link);
    void postProcessDocument(bool firstTime);
    void highlightCodeBlock(const QString &language, QTextBlock &block);

    struct CodeBlockEntry {
        QTextFrame *frame = nullptr;
        QString code;
        QtcButton *button = nullptr;
    };
    void updateCopyButtonPositions();
    void updateCopyButtonsForFontScale();
    int currentButtonSize() const;
    void withFixedTopPosition(const std::function<void()> &action);

    bool m_enableCodeCopyButton = false;
    bool m_showRulersForHeadings = false;
    QList<CodeBlockEntry> m_codeBlocks;
    bool m_isWheelZoomEnabled = false;
    qreal m_defaultFontSize = 12;
    qreal m_scale = 1.0f;
};

} // namespace Utils
