using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls.DragDrop;
using Telerik.Windows.Controls;
using Telerik.Windows.Documents;
using Telerik.Windows.Documents.Model;
using System.Diagnostics;
using System.IO;
using Telerik.Windows.Documents.Layout;

namespace OnDropBookmarks
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            RadDragAndDropManager.AddDragQueryHandler(radTreeView, OnDragQuery);
            RadDragAndDropManager.AddDropQueryHandler(radRichTextBox, OnDropQuery);
            RadDragAndDropManager.AddDragInfoHandler(radTreeView, OnDragInfo);
            RadDragAndDropManager.AddDropInfoHandler(radRichTextBox, OnDropInfo);
        }

        private void OnDragQuery(object sender, DragDropQueryEventArgs e)
        {
            RadTreeViewItem treeViewItem = e.Options.Source as RadTreeViewItem;
            if (e.Options.Status == DragStatus.DragQuery)
            {
                e.Options.Payload = treeViewItem;

                TextBlock block = new TextBlock()
                {
                    Text = treeViewItem.ToString()
                };
                e.Options.DragCue = block;
            }
            e.Handled = true;
            e.QueryResult = true;
        }

        private void OnDragInfo(object sender, DragDropEventArgs e)
        {
            //RadTreeViewItem treeViewItem = e.Options.Source as RadTreeViewItem;
            //RadTreeViewItem payload = e.Options.Payload as RadTreeViewItem;

            //if (e.Options.Status == DragStatus.DragComplete)
            //{
            //    if (payload != null)
            //    {
            //        RadTreeView treeView = treeViewItem.Parent as RadTreeView;
            //        treeView.Items.Remove(payload);
            //    }
            //}         
        }

        private void OnDropQuery(object sender, DragDropQueryEventArgs e)
        {
            e.QueryResult = e.Options.Payload != null;
            e.Handled = true;
        }

        private void OnDropInfo(object sender, DragDropEventArgs e)
        {
            marker.Visibility = Visibility.Collapsed;
            if (e.Options.Status == DragStatus.DropPossible)
            {
                RadRichTextBox rrtb = e.Options.Destination as RadRichTextBox;
                Point viewPoint = e.Options.RelativeDragPoint;
                DocumentPosition position = rrtb.ActiveEditorPresenter.GetDocumentPositionFromViewPoint(viewPoint);

                Point documentPos = rrtb.ActiveEditorPresenter.GetViewPointFromDocumentPosition(position);
                double? fontSize = rrtb.CurrentEditingStyle.GetPropertyValue(Span.FontSizeProperty) as double?;
                if (fontSize != null)
                {
                    this.marker.Height = 1.5 * (double)fontSize;
                }
                marker.Visibility = Visibility.Visible;
                marker.Margin = new Thickness(documentPos.X, documentPos.Y, 0, 0);
            }
            else if (e.Options.Status == DragStatus.DropComplete)
            {
                RadRichTextBox rrtb = e.Options.Destination as RadRichTextBox;
                Point viewPoint = e.Options.RelativeDragPoint;
                RadTreeViewItem item = e.Options.Payload as RadTreeViewItem;
                Image image = item.Item as Image;
                if (image != null)
                {
                    AddImageInBookmark(rrtb, viewPoint, image);
                }
                else
                {
                    DocumentPosition pos = rrtb.ActiveEditorPresenter.GetDocumentPositionFromViewPoint(viewPoint);
                    rrtb.Document.CaretPosition.MoveToPosition(pos);
                    Span span = new Span(((RadTreeViewItem)e.Options.Payload).Header.ToString());
                    rrtb.Document.InsertInline(span);
                }
            }
        }

        int count = 0;
        private void AddImageInBookmark(RadRichTextBox rrtb, Point viewPoint, Image image)
        {
            DocumentPosition startPosition = rrtb.ActiveEditorPresenter.GetDocumentPositionFromViewPoint(viewPoint);
            rrtb.Document.CaretPosition.MoveToPosition(startPosition);

            BookmarkRangeStart start = new BookmarkRangeStart();
            BookmarkRangeEnd end = new BookmarkRangeEnd();

            start.End = end;
            start.AnnotationID = count++;
            start.Name = "Bookmark" + start.AnnotationID;
            end.PairWithStart(start);

            ImageInline inlineImage = new ImageInline(new WriteableBitmap(image.Source as BitmapSource));
            inlineImage.Height = image.Height;
            inlineImage.Width = image.Width;

            rrtb.InsertInline(start);
            Span before = new Span("before");
            rrtb.InsertInline(before);
            rrtb.InsertLineBreak();
            rrtb.InsertInline(inlineImage);
            Span after = new Span("after");
            rrtb.InsertLineBreak();
            rrtb.InsertInline(after);            
            rrtb.InsertInline(end);
        }

        private void isInsideBookmark_Click(object sender, RoutedEventArgs e)
        {
            if (IsCaretInsideBookmark())
            {
                MessageBox.Show("True");
            }
            else
            {
                MessageBox.Show("False");
            }
        }

        private bool IsCaretInsideBookmark()
        {
            DocumentPosition caret = this.radRichTextBox.Document.CaretPosition;
            DocumentPosition bookmarkStart = new DocumentPosition(this.radRichTextBox.Document);
            DocumentPosition bookmarkEnd = new DocumentPosition(this.radRichTextBox.Document);

            foreach (BookmarkRangeStart start in this.radRichTextBox.Document.GetAllBookmarks())
            {
                var first = start.FirstLayoutBox as InlineLayoutBox;
                bookmarkStart.MoveToInline(first, first.PositionsCountInBox - 1);
                var last = start.End.FirstLayoutBox as InlineLayoutBox;
                bookmarkEnd.MoveToInline(last, last.PositionsCountInBox - 1);
                
                if (caret >= bookmarkStart && caret <= bookmarkEnd)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
