using XGame.Framework.Asset;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;


namespace XGame.Editor.Asset
{
    public static class AlphaTextureManifestExt
    {
        /// <summary>
        /// 编辑器扩展方法
        /// </summary>
        /// <param name="manifest"></param>
        /// <returns></returns>
        public static List<AtlasAlphaTextureInfo> GetAlphaTextureInfos(this AlphaTextureManifest manifest)
        {
            if (manifest != null)
            {
                var field = manifest.GetType().GetField("alphaTextureInfos", BindingFlags.NonPublic | BindingFlags.Instance);
                if (field != null)
                {
                    var infos = (AtlasAlphaTextureInfo[])field.GetValue(manifest);
                    if (infos != null)
                    {
                        return infos.Distinct().ToList();
                    }
                }
            }
            return new List<AtlasAlphaTextureInfo>();
        }
        /// <summary>
        /// 编辑器扩展方法
        /// </summary>
        /// <param name="manifest"></param>
        /// <param name="alphaTextureInfos"></param>
        public static void SetAlphaTextureInfos(this AlphaTextureManifest manifest, AtlasAlphaTextureInfo[] alphaTextureInfos)
        {
            if (manifest == null) return;
            if (alphaTextureInfos != null)
            {
                alphaTextureInfos = alphaTextureInfos.Distinct().ToArray();
                Array.Sort(alphaTextureInfos);
            }
            var field = manifest.GetType().GetField("alphaTextureInfos", BindingFlags.NonPublic | BindingFlags.Instance);
            field?.SetValue(manifest, alphaTextureInfos);

            EditorUtility.SetDirty(manifest);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }
}

