namespace Editor;

public partial class AssetBrowser
{
	/// <summary>
	/// Gets the closest open <see cref="Project"/> to the current focused widget
	/// </summary>
	public static LocalAssetBrowser Get()
	{
		LocalAssetBrowser browser;

		// 1. try to find one for the current focused window
		if ( Application.FocusWidget?.GetWindow() is DockWindow dockable )
		{
			browser = dockable.DockManager.GetDockWidget( "Asset Browser" ) as LocalAssetBrowser;
			if ( browser.IsValid() ) return browser;
		}

		// 2. try the primary instance
		browser = MainAssetBrowser.Instance.Local;
		if ( browser.IsValid() ) return browser;

		return null;
	}

	/// <summary>
	/// Gets the closest open <see cref="Project"/> to the current focused widget, or creates a new one
	/// </summary>
	public static LocalAssetBrowser GetOrCreate()
	{
		if ( Get() is { } browser )
			return browser;

		return EditorWindow.DockManager.Create<MainAssetBrowser>().Local;
	}

	/// <summary>
	/// Opens an AssetBrowser to the <paramref name="asset"/>, raising the window into view.
	/// If no AssetBrowser is open already, a new one will be opened. 
	/// </summary>
	public static void OpenTo( Asset asset, bool skipEvents = false )
	{
		var browser = GetOrCreate();
		EditorWindow.DockManager.RaiseDock( browser );
		browser.Focus( true );
		browser.FocusOnAsset( asset, skipEvents );
	}

	/// <summary>
	/// Opens an AssetBrowser to the <paramref name="entry"/> location, raising the window into view.
	/// If no AssetBrowser is open already, a new one will be opened. 
	/// </summary>
	public static void OpenTo( AssetEntry entry, bool skipEvents = false )
	{
		if ( entry.Asset is { } asset )
		{
			OpenTo( asset, skipEvents );
			return;
		}

		var browser = GetOrCreate();
		EditorWindow.DockManager.RaiseDock( browser );
		browser.Focus( true );
		browser.NavigateTo( entry.AbsolutePath );
	}
}
