// SPDX-FileCopyrightText: 2025 g10 code GmbH
// SPDX-License-Identifier: LGPL-2.1-or-later

#pragma once

#include <QTextDocumentFragment>
#include <QTextEdit>

#include <Sonnet/Speller>

#include "identity/signature.h"

namespace Sonnet
{
class Highlighter;
}

namespace MessageComposer
{
class TextPart;
class ComposerSignatures;

class BodyTextEditor : public QTextEdit
{
    Q_OBJECT

public:
    explicit BodyTextEditor(QWidget *parent);
    ~BodyTextEditor() override;

    [[nodiscard]] bool checkSpellingEnabled() const;
    void setCheckSpellingEnabled(bool check);

    [[nodiscard]] ComposerSignatures *composerSignatures() const;

    [[nodiscard]] int quoteLength(const QString &line, bool oneQuote = false) const;
    [[nodiscard]] bool isLineQuoted(const QString &line) const;

    void insertSignature(const KIdentityManagementCore::Signature &signature,
                         KIdentityManagementCore::Signature::Placement placement,
                         KIdentityManagementCore::Signature::AddedText addedText);

    void enableWordWrap(int wrapColumn);
    void disableWordWrap();

    [[nodiscard]] QString spellCheckingLanguage() const;
    void setSpellCheckingLanguage(const QString &lang);

    int linePosition() const;
    int columnNumber() const;

    QString quotePrefixName() const;

    [[nodiscard]] Sonnet::Highlighter *highlighter() const;

    void fillComposerTextPart(MessageComposer::TextPart *textPart);

Q_SIGNALS:
    void checkSpellingChanged(bool);
    void spellCheckerAutoCorrect(const QString &currentWord, const QString &autoCorrectWord);
    void languageChanged(const QString &language);
    void spellCheckStatus();

protected:
    void contextMenuEvent(QContextMenuEvent *event) override;

private:
    void slotUndoableClear();
    void slotCheckSpelling();
    void slotToggleAutoSpellCheck();
    void slotLanguageSelected();
    void slotSpellCheckerCanceled();
    void slotSpellCheckerAutoCorrect(const QString &currentWord, const QString &autoCorrectWord);
    void slotSpellCheckerMisspelling(const QString &text, int pos);
    void slotSpellCheckerFinished();
    void slotSpellCheckerCorrected(const QString &oldWord, int pos, const QString &newWord);
    void highlightWord(int length, int pos);

    QString toWrappedPlainText() const;

    ComposerSignatures *const m_composerSignatures;
    QString m_spellCheckingLanguage;
    QStringList m_ignoreSpellCheckingWords;
    QTextDocumentFragment m_originalDoc;
    bool m_checkSpellingEnabled = true;
    bool m_activateLanguageMenu = false;
    std::unique_ptr<Sonnet::Speller> m_speller = nullptr;
    Sonnet::Highlighter *m_highlighter = nullptr;
};

}
