using System.IO;
using UnityEditor;
using UnityEngine;

namespace XGame.Editor.Asset.Tools
{
    public class TextureVerifyTask
    {
        private const string asset_res = "Assets/Res/";
        public void Run()
        {
            var textureGUIDs = AssetDatabase.FindAssets("t:Texture");
            var count = 0;
            foreach (var guid in textureGUIDs)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                EditorUtility.DisplayProgressBar("检测贴图...", $"Path:{path}", (++count) / (float)textureGUIDs.Length);
                VerifyTextureByPath(path);
                //Debug.Log($"贴图:{path}", AssetDatabase.LoadMainAssetAtPath(path));
            }
            EditorUtility.ClearProgressBar();
            Debug.Log($"VerifyTextureAssets Finish.");
        }
        //[MenuItem("Assets/检测选中贴图")]
        //public static void Test()
        //{
        //    var assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
        //    VerifyTextureByPath(assetPath);
        //}
        public bool VerifyTextureByPath(string path)
        {
            if (!path.StartsWith(asset_res))
            {
                //只检测项目 Assets/目录下的资源
                //Debug.Log($"只检测项目 Assets/目录下的资源。Path:{path}");
                return true;
            }
            if (path.Contains(" "))
            {
                Debug.LogError($"贴图名字或者文件夹路径有空格符. Path:{path}", AssetDatabase.LoadAssetAtPath<Texture>(path));
                return false;
            }
            if (FileUtil.HasChinese(path))
            {
                Debug.LogError($"贴图名字或者文件夹路径包含中文字符. Path:{path}", AssetDatabase.LoadAssetAtPath<Texture>(path));
                return false;
            }
            if (!VerifyFile(path))
            {
                Debug.LogError($"贴图文件大小超标. Path:{path}");
                return false;
            }
            var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
            if (textureImporter != null)
            {
                if (textureImporter.textureType == TextureImporterType.Sprite && path.ToLower().Contains("atlas"))
                {
                    return true;
                }
                var haveAlpha = textureImporter.DoesSourceTextureHaveAlpha();
                var needVerifySize = false;
                var isTwoPower = false;
                if (!haveAlpha && textureImporter.npotScale == TextureImporterNPOTScale.None)
                {
                    needVerifySize = true;
                }
                else
                {
                    var androidSetting = textureImporter.GetPlatformTextureSettings("Android");
                    if (androidSetting.format == TextureImporterFormat.ETC2_RGBA8Crunched ||
                        androidSetting.format == TextureImporterFormat.ETC2_RGBA8 ||
                        androidSetting.format == TextureImporterFormat.ETC2_RGB4 ||
                        androidSetting.format == TextureImporterFormat.ETC_RGB4Crunched ||
                        androidSetting.format == TextureImporterFormat.ETC_RGB4 ||
                        androidSetting.format == TextureImporterFormat.Automatic)
                    {
                        needVerifySize = true;
                    }
                    else
                    {
                        var iosSetting = textureImporter.GetPlatformTextureSettings("iOS");
                        if (iosSetting.format == TextureImporterFormat.PVRTC_RGB2 ||
                            iosSetting.format == TextureImporterFormat.PVRTC_RGB4 ||
                            iosSetting.format == TextureImporterFormat.PVRTC_RGBA2 ||
                            iosSetting.format == TextureImporterFormat.PVRTC_RGBA4 ||
                            iosSetting.format == TextureImporterFormat.Automatic)
                        {
                            needVerifySize = true;
                            isTwoPower = true;
                        }
                        else
                        {
                            var defaultSetting = textureImporter.GetDefaultPlatformTextureSettings();
                            if (defaultSetting.format == TextureImporterFormat.DXT5 ||
                                defaultSetting.format == TextureImporterFormat.DXT5Crunched ||
                                defaultSetting.format == TextureImporterFormat.Automatic)
                            {
                                needVerifySize = true;
                            }
                        }
                    }
                }
                if (needVerifySize)
                {
                    var texture = AssetDatabase.LoadAssetAtPath<Texture>(path);
                    if (!VerifyTextureSize(texture, isTwoPower))
                    {
                        Debug.LogError($"贴图长宽不是4的倍数或2的幂次. Path:{path}", texture);
                        return false;
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 检测资源文件大小
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public bool VerifyFile(string assetPath)
        {
            const int fileLengthLimit = 4 * 1024 * 1024;
            var fileInfo = new FileInfo(Path.GetFullPath(assetPath));
            if (fileInfo.Exists && fileInfo.Length > fileLengthLimit)
            {
                return false;
            }
            return true;
        }
        public bool VerifyTextureSize(Texture texture, bool twoPower = false)
        {
            if (texture == null) return true;
            if (twoPower)
            {
                return Get2Flag(texture.width) && Get2Flag(texture.height);
            }
            return texture.width % 4 == 0 && texture.height % 4 == 0;
        }

        /// <summary>
        /// 判断一个数是否是2的n次幂
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private bool Get2Flag(int number)
        {
            if (number < 1) return false;
            return (number & (number - 1)) == 0;
        }
    }

}