using XGame.Editor.Asset.Processor;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;
using Object = UnityEngine.Object;

namespace XGame.Editor.Asset
{
    [Serializable]
    public struct AtlasRoot
    {
        public string path;
        public string tag;
    }
    public partial class AtlasBuildTask
    {

        /// <summary>
        /// 图集Package标签，文件夹名以标签结尾的表示该文件夹下的所有内容需要合并在一个图集里
        /// </summary>
        private const string packageTag = "pkg";
        private readonly string packageTag2 = $"_{packageTag}";

        private readonly string _ResStaticDir = $"/{PathDefine.ResStaticName}/";
        private HashSet<string> _depAssetPaths;
        /// <summary>
        /// 图集名命名类型
        /// 0:tag+文件夹名
        /// 1:文件夹路径
        /// 2:guid
        /// </summary>
        private int _atlasNameType;
        //private string[] GetAtlasPaths()
        //{
        //    var roots = AssetsConfig.AtlasRoots;
        //    //var count = 1; //临时改下
        //    var count = roots.Length;
        //    var paths = new string[count];
        //    for (var i = 0; i < count; i++)
        //    {
        //        paths[i] = roots[i].path;
        //    }
        //    return paths;
        //}
        /// <summary>
        /// 创建图集配置
        /// </summary>
        public void Run()
        {
            _atlasNameType = AssetsConfig.AtlasNameType;
            SetSpritePackerMode();
            CollectDependencies();
            CreateSpriteAtlas();
        }

        private void SetSpritePackerMode()
        {
            if (EditorSettings.spritePackerMode == UnityEditor.SpritePackerMode.AlwaysOnAtlas ||
                EditorSettings.spritePackerMode == UnityEditor.SpritePackerMode.BuildTimeOnlyAtlas)
            {
                return;
            }
            EditorSettings.spritePackerMode = UnityEditor.SpritePackerMode.BuildTimeOnlyAtlas;
        }
        /// <summary>
        /// 收集创建所有图集的spriteatlas
        /// </summary>
        private void CreateSpriteAtlas()
        {
            var directories = FileUtil.GetAtlasRoots();
            foreach (var directory in directories)
            {
                if (!Directory.Exists(directory))
                {
                    Debug.LogWarning($"Can't find atlas root:{directory}");
                    continue;
                }
                Debug.Log($"CreateAtlas Start. Root:{directory}");
                var isRaw = directory.Contains(_ResStaticDir);
                CreateAtlas(directory, 0, isRaw);
            }
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            Debug.Log($"CreateAtlas Finish. Time: {DateTime.Now}");
        }
        private bool CreateAtlas(string atlasDirectory, int layer, bool isRaw)
        {
            if (!Directory.Exists(atlasDirectory))
            {
                Debug.LogError($"Directory is not Exists. Path:{atlasDirectory}");
                return false;
            }
            //Debug.Log($"CreateAtlas atlasDirectory:{atlasDirectory}");
            var havePkgTag = HavePackageTag(atlasDirectory);
            var entities = Directory.GetFileSystemEntries(atlasDirectory);
            var texturePaths = new List<string>();
            var spriteAtlases = new List<string>();
            var hasSub = false;
            var layerLimit = AssetsConfig.AtlasLayerLimit;
            foreach (var entity in entities)
            {
                var entityPath = entity.Replace("\\", "/");
                if (Directory.Exists(entityPath))
                {//是文件夹
                    if (havePkgTag || layer >= layerLimit)
                    {
                        //最多递归3次
                        //所有子文件夹贴图
                        var subFolders = new string[] { entityPath };
                        var textureGuids = AssetDatabase.FindAssets("t:Texture", subFolders);
                        foreach(var textureGuid in textureGuids)
                        {
                            texturePaths.Add(AssetDatabase.GUIDToAssetPath(textureGuid));
                            hasSub = true;
                        }
                        //图集配置文件
                        var saGuids = AssetDatabase.FindAssets("t:SpriteAtlas", subFolders);
                        foreach(var saGuid in saGuids)
                        {
                            spriteAtlases.Add(AssetDatabase.GUIDToAssetPath(saGuid));
                        }
                    }
                    else
                    {
                        if (CreateAtlas(entityPath, layer + 1, isRaw))
                        {
                            hasSub = true;
                        }
                    }
                }
                else
                {
                    if (FileUtil.IsTextureFile(entityPath))
                    {
                        texturePaths.Add(entityPath);
                    }
                    else if (FileUtil.IsSpriteAtlas(entityPath))
                    {
                        spriteAtlases.Add(entityPath);
                    }
                }
            }
            //ResStatic下过滤没有使用的贴图
            if (isRaw && texturePaths.Count > 0)
            {
                for (int i = texturePaths.Count - 1; i >= 0; i--)
                {
                    if (!IsUsing(texturePaths[i]))
                    {
                        texturePaths.RemoveAt(i);
                    }
                }
            }
            var noAlpha = false;
            if (texturePaths.Count > 0)
            {
                var assetPath = texturePaths[0];
                try
                {
                    //取首尾两张图的属性确认该图集是否需要alpha
                    var textureImport = AssetImporter.GetAtPath(assetPath) as TextureImporter;
                    if (textureImport != null && !textureImport.DoesSourceTextureHaveAlpha())
                    {
                        assetPath = texturePaths[texturePaths.Count - 1];
                        textureImport = AssetImporter.GetAtPath(assetPath) as TextureImporter;
                        if (textureImport != null && !textureImport.DoesSourceTextureHaveAlpha())
                        {
                            noAlpha = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Read texture alpha failed. Path:{assetPath}", AssetDatabase.LoadMainAssetAtPath(assetPath));
                    Debug.LogException(ex);
                }

            }

            var atlasPath = GetAtlasPath(atlasDirectory);

            foreach (var lastAtlas in spriteAtlases)
            { //删除旧的图集
                if (texturePaths.Count > 0 && lastAtlas.Equals(atlasPath))
                { //保留同名图集
                    continue;
                }
                //Debug.Log($"Delete Atlas: {lastAtlas}");
                UnityEditor.FileUtil.DeleteFileOrDirectory(lastAtlas);
            }
            if (texturePaths.Count > 0)
            {
                var atlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(atlasPath);
                var isNew = false;
                if (atlas == null)
                {
                    atlas = new SpriteAtlas();
                    isNew = true;
                }
                var preset = AssetsConfig.SpriteAtlasPreset;
                if (preset != null)
                {
                    preset.ApplyTo(atlas);
                    if (noAlpha)
                    {
                        //Android
                        var androidPlatformSettings = atlas.GetPlatformSettings("Android");
                        androidPlatformSettings.overridden = true;
                        androidPlatformSettings.format = TextureImporterFormat.ETC2_RGB4;
                        atlas.SetPlatformSettings(androidPlatformSettings);
                    }
                }
                else
                {
                    var packingSettings = atlas.GetPackingSettings();
                    packingSettings.enableRotation = false;
                    packingSettings.enableTightPacking = false;
                    atlas.SetPackingSettings(packingSettings);
                    //设置Texture属性
                    var textureSettings = atlas.GetTextureSettings();
                    textureSettings.generateMipMaps = false;
                    textureSettings.readable = false;
                    atlas.SetTextureSettings(textureSettings);
                    //设置Platform属性
                    //default
                    var defaultPlatformSettings = atlas.GetPlatformSettings("DefaultTexturePlatform");
                    defaultPlatformSettings.format = TextureImporterFormat.Automatic;
                    defaultPlatformSettings.maxTextureSize = 2048;
                    defaultPlatformSettings.textureCompression = TextureImporterCompression.Compressed;
                    atlas.SetPlatformSettings(defaultPlatformSettings);
                    //Android
                    var androidPlatformSettings = atlas.GetPlatformSettings("Android");
                    androidPlatformSettings.overridden = true;
                    androidPlatformSettings.allowsAlphaSplitting = false;
                    androidPlatformSettings.androidETC2FallbackOverride = AndroidETC2FallbackOverride.UseBuildSettings;
                    androidPlatformSettings.format = noAlpha ? TextureImporterFormat.ETC2_RGB4 : TextureImporterFormat.ETC2_RGBA8;
                    atlas.SetPlatformSettings(androidPlatformSettings);
                    //iOS
                    var iosPlatformSettings = atlas.GetPlatformSettings("iPhone");
                    iosPlatformSettings.overridden = true;
                    iosPlatformSettings.allowsAlphaSplitting = false;
                    iosPlatformSettings.format = TextureImporterFormat.ASTC_5x5;
                    atlas.SetPlatformSettings(iosPlatformSettings);
                }

                var atlasName = Path.GetFileNameWithoutExtension(atlasPath);
                atlas.name = atlasName;
                //先删除旧数据
                atlas.Remove(atlas.GetPackables());
                if (isRaw || hasSub)
                {
                    // 排序
                    var count = texturePaths.Count;
                    //if (count > 1) texturePaths.Sort();
                    var textureObjs = new Object[count];
                    for (var i = 0; i < count; i++)
                    {
                        textureObjs[i] = AssetDatabase.LoadMainAssetAtPath(texturePaths[i]);
                    }
                    atlas.Add(textureObjs);
                }
                else
                {
                    atlas.Add(new Object[] { AssetDatabase.LoadMainAssetAtPath(atlasDirectory) });
                }
                if (isNew)
                {
                    AssetDatabase.CreateAsset(atlas, atlasPath);
                }
                EditorUtility.SetDirty(atlas);
                //Debug.Log($"Save Atlas: {atlasPath}");
                return true;
            }
            return hasSub;
        }
        /// <summary>
        /// 判断一个图集文件夹是否有Package标签
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool HavePackageTag(string path)
        {
            return path.EndsWith(packageTag, StringComparison.OrdinalIgnoreCase) || path.Contains(packageTag2, StringComparison.OrdinalIgnoreCase);
        }
        private System.Text.StringBuilder tempSb = new System.Text.StringBuilder();
        private string GetAtlasPath(string path)
        {
            switch (_atlasNameType)
            {
                case 2:
                    {
                        //使用guid做图集名
                        var guid = AssetDatabase.AssetPathToGUID(path);
                        return $"{path}/atlas_{guid.ToLower()}.spriteatlas";
                    }
                case 1:
                    //使用文件夹路径做图集名
                    return $"{path}/{path.Substring(PathDefine.AssetsRelative.Length).ToLower().Replace('/', '_')}.spriteatlas";
                default:
                    {
                        var startIdx = 0;
                        int index;
                        while ((index = path.IndexOf('/', startIdx)) != -1 && index < path.Length)
                        {
                            // 取文件夹名首字符合并做tag，这样做可能会有重复的图集名
                            tempSb.Append(path[index + 1]);
                            startIdx = index + 1;
                        }
                        var tag = tempSb.ToString().ToLower();
                        tempSb.Clear();
                        //tag加文件夹名字
                        return $"{path}/atlas_{tag}_{Path.GetFileName(path).ToLower()}.spriteatlas";
                    }
            }
        }
        #region 引用记录
        private void CollectDependencies()
        {
            var productAssetsRoots = FileUtil.GetProductAssetsRoots(true);
            var assetGuids = AssetDatabase.FindAssets("", productAssetsRoots);
            var assetPaths = new List<string>();
            foreach (var assetGuid in assetGuids)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
                if (Directory.Exists(assetPath) || FileUtil.IsFileIgnore(assetPath) || FileUtil.IsTextureFile(assetPath))
                    continue;
                assetPaths.Add(assetPath);
            }
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            var dependencies = AssetDatabase.GetDependencies(assetPaths.ToArray(), true);
            sw.Stop();
            var depAssetPaths = new HashSet<string>();

            //var rawPaths = new HashSet<string>();
            //var roots = AssetsConfig.AtlasRoots;
            //foreach (var root in roots)
            //{
            //    if (root.path.Contains(PathDefine.ResStaticName))
            //    {
            //        rawPaths.Add(root.path);
            //    }
            //}
            foreach (var dep in dependencies)
            {
                if (dep.Contains(_ResStaticDir, StringComparison.OrdinalIgnoreCase))
                {
                    depAssetPaths.Add(dep);
                }
            }
            _depAssetPaths = depAssetPaths;
            Debug.Log($"[XBuild] Atlas GetDependencies Time:{sw.ElapsedMilliseconds}");
        }
        private bool IsUsing(string path)
        {
            return _depAssetPaths.Contains(path);
        }
        #endregion
    }
}
