using Avalonia;
using AvaloniaEdit;
using AvaloniaEdit.Document;

namespace MarkdownEditor.Views;

/// <summary>
/// Helper class for binding AvaloniaEdit TextDocument to MVVM view models.
/// Provides an attached property to enable two-way binding of the Document property.
/// </summary>
public static class TextEditorHelper
{
    /// <summary>
    /// Attached property for binding a TextDocument to a TextEditor control.
    /// </summary>
    public static readonly AttachedProperty<TextDocument?> DocumentProperty =
        AvaloniaProperty.RegisterAttached<TextEditor, TextDocument?>(
            "Document",
            typeof(TextEditorHelper));

    /// <summary>
    /// Gets the document attached to the specified TextEditor.
    /// </summary>
    /// <param name="editor">The TextEditor control.</param>
    /// <returns>The attached TextDocument, or null if none is attached.</returns>
    public static TextDocument? GetDocument(TextEditor editor)
    {
        return editor.GetValue(DocumentProperty);
    }

    /// <summary>
    /// Sets the document to attach to the specified TextEditor.
    /// </summary>
    /// <param name="editor">The TextEditor control.</param>
    /// <param name="value">The TextDocument to attach.</param>
    public static void SetDocument(TextEditor editor, TextDocument? value)
    {
        editor.SetValue(DocumentProperty, value);
    }

    static TextEditorHelper()
    {
        DocumentProperty.Changed.AddClassHandler<TextEditor>(OnDocumentChanged);
    }

    private static void OnDocumentChanged(TextEditor editor, AvaloniaPropertyChangedEventArgs e)
    {
        if (e.NewValue is TextDocument document)
        {
            editor.Document = document;
        }
    }
}

