using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace BS.Shared.Extensions
{
    public static class DependencyObjectExtensions
    {
        public static T FindFirstVisualChild<T>(this DependencyObject pObj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(pObj); i++)
            {
                DependencyObject lChild = VisualTreeHelper.GetChild(pObj, i);
                if (lChild != null && lChild is T)
                {
                    return (T)lChild;
                }
                else
                {
                    T lChildOfChild = lChild.FindFirstVisualChild<T>();
                    if (lChildOfChild != null)
                    {
                        return lChildOfChild;
                    }
                }
            }

            return null;
        }

        public static IEnumerable<DependencyObject> GetAllChildren(this DependencyObject pObj)
        {
            var result = new List<DependencyObject>();

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(pObj); i++)
            {
                var lChild = VisualTreeHelper.GetChild(pObj, i);
                result.Add(lChild);
                result.AddRange(GetAllChildren(lChild));
            }

            return result;
        }

        public static T GetVisualParent<T>(this DependencyObject pObj) where T : DependencyObject
        {
            var parent = pObj;
            while (parent != null)
            {
                parent = VisualTreeHelper.GetParent(parent) as Visual;
                if (parent != null && parent.GetType() == typeof(T))
                    return parent as T;
            }

            return parent as T;
        }
    }
}