using System;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;

namespace QsprMiscShared.Utilities;

public static class Extensions
{
	private static Action EmptyDelegate = delegate
	{
	};

	public static bool InvokeRequired(this UIElement uiELement)
	{
		if (Thread.CurrentThread == uiELement.Dispatcher.Thread)
		{
			return false;
		}
		return true;
	}

	public static void BeginInvoke(this UIElement uiElement, Action action)
	{
		uiElement.Dispatcher.BeginInvoke(action);
	}

	public static void Invoke(this UIElement uiElement, Action action)
	{
		uiElement.Dispatcher.Invoke(action, new object[0]);
	}

	public static object Invoke(this UIElement uiElement, Delegate function, object[] args = null)
	{
		return uiElement.Dispatcher.Invoke(function, args);
	}

	public static T FindName<T>(this FrameworkElement element, string name) where T : class
	{
		return element.FindName(name) as T;
	}

	public static T FindParent<T>(this DependencyObject depObject) where T : DependencyObject
	{
		DependencyObject parent = VisualTreeHelper.GetParent(depObject);
		if (parent is T)
		{
			return parent as T;
		}
		if (parent == null)
		{
			return null;
		}
		return parent.FindParent<T>();
	}

	public static void Refresh(this UIElement uiElement)
	{
		uiElement.Dispatcher.BeginInvoke(DispatcherPriority.Render, EmptyDelegate);
	}
}
