using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

namespace XGame.Editor.Asset.Tools
{
    internal class AtlasAssetInfoItem : IReorderableItem, System.IDisposable, IReorderableItemData<AtlasAssetInfoData>
    {
        private AtlasAssetInfoData _data;
        private string _assetName;
        private SpriteAtlas _assetObj;
        private GUIContent _atlasDescription;
        /// <summary>
        /// 单位: M
        /// </summary>
        public double TotalSize { get; private set; }
        public float Height { get; private set; }

        public AtlasAssetInfoData Data => _data;

        public AtlasAssetInfoItem(AtlasAssetInfoData data)
        {
            _data = data;
            var assetPath = data.assetPath;
            _assetName = Path.GetFileNameWithoutExtension(assetPath);
            _assetObj = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(assetPath);
            ReadAtlasTextures();
        }
        private void ReadAtlasTextures()
        {
            //SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { _assetObj }, EditorUserBuildSettings.activeBuildTarget);
            MethodInfo getPreviewTextureMI = typeof(SpriteAtlasExtensions).GetMethod("GetPreviewTextures", BindingFlags.Static | BindingFlags.NonPublic);
            var atlasTextures = (Texture2D[])getPreviewTextureMI.Invoke(null, new System.Object[] { _assetObj });
            double size = 0;
            TextureFormat format = TextureFormat.ETC2_RGBA8;
            var count = atlasTextures != null ? atlasTextures.Length : 0;
            if (count > 0)
            {
                foreach (var texture in atlasTextures)
                {
                    format = texture.format;
                    var bpp = GetFormatBPP(format);
                    size += texture.width * texture.height * bpp / (1024 * 1024 * 8);
                }
            }
            TotalSize = size;
            _atlasDescription = GetDescriptionGUIContent(count, size);
            _atlasDescription.text = $"图集压缩格式: {format}   贴图数量:{count}   占用内存: {size.ToString("F3")}M";
        }
        private float GetFormatBPP(TextureFormat format)
        {
            switch (format)
            {
                case TextureFormat.ETC_RGB4:
                case TextureFormat.PVRTC_RGB4:
                case TextureFormat.PVRTC_RGBA4:
                case TextureFormat.ETC2_RGB:
                case TextureFormat.DXT1:
                    return 4;
                case TextureFormat.ETC2_RGBA8:
                case TextureFormat.DXT5:
                case TextureFormat.ASTC_4x4:
                    return 8;
                case TextureFormat.ASTC_5x5:
                    return 5.12f;
                case TextureFormat.ASTC_6x6:
                    return 3.56f;
                case TextureFormat.PVRTC_RGB2:
                case TextureFormat.PVRTC_RGBA2:
                case TextureFormat.ASTC_8x8:
                    return 2;
                case TextureFormat.ASTC_10x10:
                    return 1.28f;
                case TextureFormat.ASTC_12x12:
                    return 0.89f;
            }
            return 32;
        }
        private GUIContent GetDescriptionGUIContent(int textureCount, double memorySize)
        {
            string iconName;
            if (textureCount > 4 || memorySize >= 12)
            {
                iconName = "console.erroricon";
            }
            else if (textureCount > 2 || memorySize >= 8)
            {
                iconName = "console.warnicon";
            }
            else
            {
                iconName = "console.infoicon";
            }
            var icon = EditorGUIUtility.IconContent(iconName);
            var guiContent = new GUIContent(icon.image);
            return guiContent;
        }
        void IReorderableItem.OnGUI(Rect rect)
        {
            Height = 0;
            var lineH = EditorGUIUtility.singleLineHeight;
            var tempRect = rect;
            tempRect.x += 14;
            tempRect.width -= 14;
            tempRect.height = lineH;
            EditorGUI.LabelField(tempRect, _atlasDescription);
            tempRect.y += lineH;
            Height += lineH;
            //展示区域，禁止操作
            EditorGUI.BeginDisabledGroup(true);
            //var assetContent = new GUIContent("Asset", "Asset Object");
            EditorGUI.ObjectField(tempRect, _assetName, _assetObj, typeof(SpriteAtlas), false);
            tempRect.y += lineH;
            Height += lineH;
            if (_data.sprites != null)
            {
                tempRect.x += 14;
                tempRect.width -= 14;
                foreach (var spritePath in _data.sprites)
                {
                    var fileName = Path.GetFileNameWithoutExtension(spritePath);
                    EditorGUI.ObjectField(tempRect, fileName, AssetDatabase.LoadMainAssetAtPath(spritePath), typeof(Object), false);
                    tempRect.y += lineH;
                    Height += lineH;
                }
            }

            EditorGUI.EndDisabledGroup();

        }

        void System.IDisposable.Dispose()
        {
            _data = null;
            _assetObj = null;
        }
    }
}
