using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;

public class FindReferencesWindow : EditorWindow
{
    private Object targetResource;
    private readonly List<string> references = new();

    [MenuItem("Tool/Find References Window")]
    public static void ShowWindow()
    {
        GetWindow(typeof(FindReferencesWindow));
    }

    [MenuItem("Assets/Find All References in Assets")]
    private static void FindReferencesAndPingMenuItem()
    {
        Object targetResource = Selection.activeObject;
        FindReferencesWindowBySource(targetResource);
    }

    public static void FindReferencesWindowBySource(Object targetResource)
    {
        FindReferencesWindow window = GetWindow<FindReferencesWindow>();
        window.targetResource = targetResource;
        window.Show();
        window.FindReferences();
    }

    void OnGUI()
    {
        GUILayout.Label("Find References", EditorStyles.boldLabel);
        targetResource = EditorGUILayout.ObjectField("Select Resource", targetResource, typeof(Object), true);

        if (GUILayout.Button("Find References"))
        {
            FindReferences();
        }

        GUILayout.Space(20);

        GUILayout.Label("References:", EditorStyles.boldLabel);
        foreach (var reference in references)
        {

            GUILayout.BeginHorizontal();
            GUILayout.Label(reference);
            if (GUILayout.Button("Open Folder"))
            {
                OpenFolder(reference);
            }

            if (GUILayout.Button("Ping"))
            {
                var obj = AssetDatabase.LoadAssetAtPath<Object>(reference);
                EditorGUIUtility.PingObject(obj);
            }

            GUILayout.EndHorizontal();
        }
    }

    private void FindReferences()
    {
        references.Clear();

        if (targetResource == null)
        {
            Debug.LogWarning("No resource selected.");
            return;
        }

        string assetPath = AssetDatabase.GetAssetPath(targetResource);
        string[] assets = AssetDatabase.FindAssets("t:Object");

        foreach (string assetGUID in assets)
        {
            string assetPathTemp = AssetDatabase.GUIDToAssetPath(assetGUID);
            string[] dependencies = AssetDatabase.GetDependencies(assetPathTemp);

            foreach (string dependency in dependencies)
            {
                if (dependency == assetPath)
                {
                    references.Add(assetPathTemp);
                }
            }
        }

        Repaint();
    }

    private void OpenFolder(string path)
    {
        string folderPath = Path.GetDirectoryName(path);
        if (!string.IsNullOrEmpty(folderPath) && Directory.Exists(folderPath))
        {
            EditorUtility.RevealInFinder(folderPath);
        }
    }

}