using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using UnityEditor;
using UnityEngine;
namespace EditorUtils
{
    public class ResRepeatCheckerWindow : EditorWindow
    {

        Vector2 scrollPos = Vector2.zero;
        Dictionary<string, string> md5dic = new ();
        Dictionary<string, List<string>> md5repeatDic = new ();

        [MenuItem("Tool/ResRepeatCheckerWindow")]
        static void OpenRaycastResultWindow()
        {
            ResRepeatCheckerWindow win = EditorWindow.GetWindow<ResRepeatCheckerWindow>();
            win.titleContent = new GUIContent("重复资源检查");
        }


        void CheckRepeatAsset()
        {
            md5dic.Clear();
            md5repeatDic.Clear();

            string[] prefabGuids = AssetDatabase.FindAssets("t:prefab", new string[] { "Assets" });
            Debug.Log("预制体" + prefabGuids.Length);

            string[] sceneGuids = AssetDatabase.FindAssets("t:Scene", new string[] { "Assets" });
            Debug.Log("场景" + sceneGuids.Length);

            string[] paths = prefabGuids.Concat(sceneGuids).ToArray();

            foreach (var prefabGuid in paths)
            {
                string soucePath = AssetDatabase.GUIDToAssetPath(prefabGuid); // 从GUID拿到资源的路径

                string[] depend = AssetDatabase.GetDependencies(soucePath, true);
                foreach(string assetPath in depend)
                {
                    // Debug.Log(assetPath);
                    AssetImporter importer = AssetImporter.GetAtPath(assetPath);
                    // 满足贴图和模型资源
                    if (importer is TextureImporter || importer is AudioImporter || importer is ModelImporter)
                    {

                        string md5 = GetMD5Hash(Path.Combine(Directory.GetCurrentDirectory(), assetPath)); //获取md5
                        string path;
                        md5dic.TryGetValue(md5, out path);
                        if (path == null)
                        {
                            md5dic[md5] = assetPath;
                        }
                        else
                        {
                            if (path != assetPath)
                            {
                                Debug.LogFormat("资源重复{0}，{1}：位置{2}", path, assetPath, soucePath);
                                if (!md5repeatDic.ContainsKey(md5)) md5repeatDic[md5] = new List<string>();
                                if (!md5repeatDic[md5].Contains(assetPath))
                                    md5repeatDic[md5].Add(assetPath);
                                if (!md5repeatDic[md5].Contains(path))
                                    md5repeatDic[md5].Add(path);
                            }
                        }
                    }
                    else
                    {

                    }
                }
            }
        }

        static string GetMD5Hash(string filePath)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            return BitConverter.ToString(md5.ComputeHash(File.ReadAllBytes(filePath))).Replace("-", "").ToLower();
        }



        private void OnGUI()
        {

            GUILayout.Label("检查Assets下重复使用资源");
            GUILayout.Label("包括[Texture][Audio][Model]");
            if (GUILayout.Button("查找重复资源"))
            {
                CheckRepeatAsset();
            }
            scrollPos = GUILayout.BeginScrollView(scrollPos);

            foreach (var item in md5repeatDic)
            {
                GUILayout.BeginVertical();
                GUILayout.Label($"md5:{item.Key}");
                foreach (var path in item.Value)
                {
                    GUILayout.BeginHorizontal();
                    if (GUILayout.Button(path))
                    {
                        UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
                        EditorGUIUtility.PingObject(obj);
                    }

                    if(GUILayout.Button("find reference"))
                    {
                        var obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
                        FindReferencesWindow.FindReferencesWindowBySource(obj);
                    }

                    GUILayout.EndHorizontal();
                }
                GUILayout.EndVertical();
                GUILayout.Space(20f);
            }
            GUILayout.EndScrollView();
        }


    }
}

