using System;
using System.ComponentModel.Composition;
using System.Windows.Controls;
using Telerik.Windows;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.DragDrop;

namespace TaskIt.Modules.Tasks.Core
{
    [Export]
    public class ApplicationDragDrop
    {
        /// <summary>
        /// This class initializes application-wide drag-drop rules. We register them with class event handlers and this way we do not have
        /// to ever know the instances of where this effect takes place.
        /// </summary>
        public ApplicationDragDrop()
        {
            EventManager.RegisterClassHandler(typeof(Control), RadDragAndDropManager.DropInfoEvent, new EventHandler<DragDropEventArgs>(OnControlDropInfo));
            EventManager.RegisterClassHandler(typeof(RadTreeViewItem), RadDragAndDropManager.DropQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnTreeViewItemDropQuery));           
        }

        private static void OnControlDropInfo(object sender, DragDropEventArgs e)
        {
            // This event handler gives feedback to the user that a drop is possible by setting the background of the
            // element. Please note that the event is not handled, because there really is no concrete action that we do.
            var control = sender as Control;
            if (control == null || control != e.Options.Destination)
            {
                return;
            }

            switch (e.Options.Status)
            {
                case DragStatus.DropPossible:
                    control.Background = DataTemplateProvider.Instance.DropPossibleBackground;
                    break;
                case DragStatus.DropCancel:
                case DragStatus.DropComplete:
                case DragStatus.DropImpossible:
                    control.ClearValue(Control.BackgroundProperty);
                    break;
            }
        }

        private static void OnTreeViewItemDropQuery(object sender, DragDropQueryEventArgs e)
        {
            // We always want to expand the underlying treeViewItems if they are collapsed when the user drags over them.
            var treeViewItem = sender as RadTreeViewItem;
            if (treeViewItem != null && !treeViewItem.IsExpanded && e.Options.Status == DragStatus.DropDestinationQuery)
            {
                treeViewItem.IsExpanded = true;
            }
        }
    }
}
