using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
public class HierarchyIcons : MonoBehaviour
{
    static HierarchyIcons()
    {
        // Subscribe to hierarchy window GUI events
        EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI;
    }

    static void OnHierarchyGUI(int instanceID, Rect selectionRect)
    {
        // only proceed during the repaint event
        if (Event.current.type != EventType.Repaint) return;

        // get the gameobject from the instanceid
        GameObject obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject;

        // proceed if a valid gameobject is found
        if (obj != null)
        {
            // get the custom icon, skipping default unity icons
            Texture2D icon = GetGameObjectIcon(obj);

            if (icon != null)
            {
                // size of the icon (ensuring it's square)
                float size = 12f;

                // adjust the x position to align with the right-side Cinemachine icon
                // reducing 20 pixels from xMax to line up with Cinemachine icon
                Rect iconRect = new Rect(selectionRect.xMax - 15, selectionRect.yMin + (selectionRect.height - size) / 2, size, size);

                // draw the custom icon at the adjusted position
                GUI.DrawTexture(iconRect, icon);
            }
        }
    }



    static Texture2D GetGameObjectIcon(GameObject obj)
    {
        // Use EditorGUIUtility.ObjectContent to get the icon
        GUIContent iconContent = EditorGUIUtility.ObjectContent(obj, obj.GetType());

        if (iconContent != null && iconContent.image is Texture2D iconTexture)
        {
            // Check if the image is one of Unity's default icons
            if (IsDefaultIcon(iconTexture))
            {
                return null; // Skip default icons like the Unity cube
            }
            return iconTexture; // Return the custom icon if it's not default
        }
        return null; // No icon found
    }

    // Method to determine if an icon is a default Unity icon
    static bool IsDefaultIcon(Texture2D icon)
    {
        // Default Unity icons often start with "d_" or "_d", especially in dark mode
        // You can check for the default Unity cube icon name specifically
        return icon.name == "Prefab Icon" || icon.name.StartsWith("d_") || icon.name.StartsWith("sv_icon");
    }
}