using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class AppAssetChecker
{
    [UnityEditor.InitializeOnLoadMethod]
    static void setup()
    {
        Type assetCheckerType = FindType("iHuman.UnitySz.Editor.AssetChecker");

        if (assetCheckerType != null)
        {
            Debug.Log("AssetChecker not null");
            Debug.Log("AppAssetChecker setup");

            // 关闭asset修改后的自动检测
            InvokeStaticMethod(assetCheckerType, "DisableAutoCheck");

            Type[] taskTypes = {
                FindType("iHuman.UnitySz.Editor.PostfixCheckTask"),
                FindType("iHuman.UnitySz.Editor.FilenameCheckTask"),
                FindType("iHuman.UnitySz.Editor.ImageCheckTask")
            };

            if (!Array.Exists(taskTypes, taskType => taskType == null))
            {
                SetStaticField(assetCheckerType, "postfixTasks", CreateGenericList(taskTypes[0], new object[]{
                    Activator.CreateInstance(taskTypes[0], "Assets/", false, new string[]{"Assets/app/Native/TextMeshPro"}, null)
                }));

                SetStaticField(assetCheckerType, "filenameTasks", CreateGenericList(taskTypes[1], new object[]{
                    Activator.CreateInstance(taskTypes[1], "Assets/", false, new string[]{"Assets/app/Native/TextMeshPro", "Assets/common/plugin/spine"}, null)
                }));

                SetStaticField(assetCheckerType, "imageTasks", CreateGenericList(taskTypes[2], new object[]{
                    Activator.CreateInstance(taskTypes[2], "Assets/", false, null, @".*\.jpg|.*\.png")
                }));
            }
            else
            {
                Debug.Log("One or more task types are missing");
            }
        }
        else
        {
            Debug.Log("AssetChecker null");
        }
    }

    static Type FindType(string typeName)
    {
        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach (Assembly assembly in assemblies)
        {
            Type type = assembly.GetType(typeName);
            if (type != null)
            {
                return type;
            }
        }
        return null;
    }

    static void InvokeStaticMethod(Type type, string methodName)
    {
        MethodInfo method = type.GetMethod(methodName);
        method?.Invoke(null, null);
    }

    static void SetStaticField(Type type, string fieldName, object value)
    {
        FieldInfo field = type.GetField(fieldName);
        field?.SetValue(null, value);
    }

    static object CreateGenericList(Type itemType, object[] items)
    {
        Type listType = typeof(List<>).MakeGenericType(itemType);
        object list = Activator.CreateInstance(listType);

        MethodInfo addMethod = listType.GetMethod("Add");
        foreach (object item in items)
        {
            addMethod.Invoke(list, new[] { item });
        }

        return list;
    }
}
