using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace ChatController.Core
{
    public class OwnChatRichTextBox : RichTextBox
    {
        public ObservableCollection<Inline> InlineList
        {
            get => (ObservableCollection<Inline>)GetValue(InlineListProperty);
            set => SetValue(InlineListProperty, value);
        }

        public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register("InlineList", typeof(ObservableCollection<Inline>), typeof(OwnChatRichTextBox), new UIPropertyMetadata(null, OnPropertyChanged));

        public static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is null)
            {
                return;
            }

            ((OwnChatRichTextBox)sender).Document = GetCustomDocument(e.NewValue as ObservableCollection<Inline>);

            if(sender is OwnChatRichTextBox ownChatRichTextBox)
            {
                ownChatRichTextBox.Document = GetCustomDocument(e.NewValue as ObservableCollection<Inline>);
                ownChatRichTextBox.Width = ownChatRichTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 20;
            }
        }

        private static FlowDocument GetCustomDocument(IEnumerable<Inline> inlines)
        {
            var flowDocument = new FlowDocument();
            var paragraph = new Paragraph
            {
                Margin = new Thickness(0) // remove indent between paragraphs
            };

            paragraph.Inlines.AddRange(inlines);

            flowDocument.Blocks.Add(paragraph);

            return flowDocument;
        }
    }
}
