// 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;
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);

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

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

protected:
    void changeEvent(QEvent *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 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;

    bool m_enableCodeCopyButton = false;
    bool m_showRulersForHeadings = false;
    QList<CodeBlockEntry> m_codeBlocks;
};

} // namespace Utils
