using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace BS.Shared.Extensions
{
    public static class TreeViewExtensions
    {
        public static T GetDataItemUnderMouse<T>(this TreeView t, MouseEventArgs mouse) where T : class
        {
            var i = t.GetTreeViewItemUnderMouse(mouse);
            if (i == null)
            {
                return null;
            }

            return i.Header as T;
        }

        public static TreeViewItem GetTreeViewItemUnderMouse(this TreeView t, MouseEventArgs mouse)
        {
            return t.GetTreeViewItems().LastOrDefault(
                i =>
                    {
                        Rect bounds = VisualTreeHelper.GetDescendantBounds(i);
                        Point mousePos = mouse.GetPosition(i);
                        return bounds.Contains(mousePos);
                    });
        }

        public static List<TreeViewItem> GetTreeViewItems(this TreeView t)
        {
            var result = new List<TreeViewItem>();
            var queue = new Queue<ItemsControl>(new[] { t });

            while (queue.Count > 0)
            {
                var level = queue.Dequeue();
                for (int i = 0; i < level.Items.Count; i++)
                {
                    var item = level.ItemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
                    if (item != null)
                    {
                        result.Add(item);
                        queue.Enqueue(item);
                    }
                }
            }

            return result;
        }
    }
}