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

using Prism.Events;
using Valg.EVA.Skanning.UserInterfaceElements.LightBox;

namespace Valg.EVA.Skanning.UserInterfaceElements.Help
{
    public static class UIExtensions
    {
        public static void ShowHelpWindow(this IEventAggregator eventAggregator)
        {
            eventAggregator.ShowHelpWindow(null);
        }

        public static void ShowHelpWindow(this IEventAggregator eventAggregator, Window root)
        {
            var locator = ServiceLocator.Current;
            var viewModel = locator.GetInstance<HelpViewModel>();
            viewModel.Resource = GetName(root);

            eventAggregator.GetEvent<ShowLightBoxEvent>()
                .Publish(new LightBoxEventArgs(typeof (HelpView), viewModel));
        }

        private static string GetName(Window root)
        {
            root = root ?? Application.Current.MainWindow;
            var items = root.GetChildrenRecursively(c => c is IHelpContributor);
            var name = HelpContributionIds.Hovedside;
            var firstMatch = items.FirstOrDefault();
            if (firstMatch != null)
            {
                var asHelpContributor = (IHelpContributor) firstMatch;
                name = asHelpContributor.HelpContributionId;
            }
            return name;
        }

        public static IEnumerable<DependencyObject> GetChildrenRecursively(this DependencyObject root, Func<DependencyObject, bool> filter = null)
        {
            var children = new List<DependencyObject> {root};
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
                children.AddRange(GetChildrenRecursively(VisualTreeHelper.GetChild(root, i), filter));

            var userControls = children.Where(o => o is UserControl || o is Window);
            if (filter != null)
                userControls = userControls.Where(filter);

            return userControls;
        }
    }
}
