using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine.U2D;

namespace XGame.Editor.Build.AssetBundles
{
    public class AtlasBundleCollector
    {
        private class AtlasInfo
        {
            public string key;
            public string[] assetPaths;
        }
        private BundleContext _context;
        /// <summary>
        /// key: sprite的assetPath
        /// value:AtlasInfos
        /// </summary>
        private Dictionary<string, AtlasInfo> _atlasInfoMap;
        public AtlasBundleCollector(BundleContext context)
        {
            _context = context;
            _atlasInfoMap = new Dictionary<string, AtlasInfo>();
        }
        public bool Collect()
        {
            var directories = Asset.FileUtil.GetAtlasRoots();
            var assetPaths = new HashSet<string>();
            var registedPaths = new HashSet<string>();
            //图集的alpha texture信息
            //var atlasAlphaMap = AtlasHelper.GetAtlasAlphaTextureMap();
            var guids = AssetDatabase.FindAssets("t:SpriteAtlas", directories);
            foreach (var guid in guids)
            {
                var atlasPath = AssetDatabase.GUIDToAssetPath(guid);
                var atlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(atlasPath);
                //Debug.Log($"atlasPath:{atlasPath} name:{atlas.name}", atlas);
                var objs = atlas.GetPackables();
                foreach (var obj in objs)
                {
                    var assetPath = AssetDatabase.GetAssetPath(obj);
                    if (Directory.Exists(assetPath))
                    {
                        //是文件夹
                        var temps = Asset.FileUtil.FindFiles(assetPath, Asset.FileUtil.texturePatterns, SearchOption.TopDirectoryOnly);
                        foreach (var temp in temps)
                        {
                            if (!registedPaths.Contains(temp) && !assetPaths.Contains(temp))
                            {
                                registedPaths.Add(temp);
                                assetPaths.Add(temp);
                            }
                        }
                    }
                    else if (!registedPaths.Contains(assetPath) && !assetPaths.Contains(assetPath))
                    {
                        // 贴图
                        registedPaths.Add(assetPath);
                        assetPaths.Add(assetPath);
                    }
                }
                //if (!_context.filePaths.Contains(atlasPath) && !assetPaths.Contains(atlasPath))
                //{
                //    // SpriteAtlas文件，sbp打包依赖该文件过滤贴图的原始文件，因此该文件也需要参与打包
                //    assetPaths.Add(atlasPath);
                //    _context.filePaths.Add(atlasPath);
                //}
                //alpha texture也打包进图集
                //if (atlasAlphaMap.TryGetValue(atlas.name, out var alphaTextureGUIDs))
                //{
                //    foreach (var alphaGUID in alphaTextureGUIDs)
                //    {
                //        var alphaAssetPath = AssetDatabase.GUIDToAssetPath(alphaGUID);
                //        Debug.Log($"Atals Alpha Texture Path:{alphaAssetPath}", AssetDatabase.LoadMainAssetAtPath(alphaAssetPath));
                //        if (!_context.filePaths.Contains(alphaAssetPath) && !assetPaths.Contains(alphaAssetPath))
                //        {
                //            assetPaths.Add(alphaAssetPath);
                //            _context.filePaths.Add(alphaAssetPath);
                //        }
                //    }
                //}
                if (assetPaths.Count > 0)
                {
                    var assetNames = _context.ToArrayBySort(assetPaths);
                    assetPaths.Clear();
                    if (atlasPath.Contains(_context.ResStaticDir))
                    {
                        _context.AddRawAssetBundle(assetNames, guid, false);
                    }
                    else
                    {
                        // 允许Addressable的图集合并打在同一个ab里
                        var info = new AtlasInfo()
                        {
                            key = guid,
                            assetPaths = assetNames
                        };
                        foreach (var assetPath in assetNames)
                        {
                            _atlasInfoMap.Add(assetPath, info);
                        }
                        // TODO
                        //_context.bundleBuildMap.TryAdd(_context.CreateBundleBuild(assetNames));
                    }
                }
            }
            return true;
        }
        public bool IsAtlasAssetPath(string assetPath)
        {
            return _atlasInfoMap.ContainsKey(assetPath);
        }
        public string[] PopAtlasAssetPaths(string assetPath)
        {
            var info = _atlasInfoMap[assetPath];
            foreach (var path in info.assetPaths)
            {
                _atlasInfoMap.Remove(path);
            }
            return info.assetPaths;
        }
        /// <summary>
        /// 处理剩余的Addressable的图集
        /// </summary>
        public void ToBundleBuilds()
        {
            var values = _atlasInfoMap.Values.Distinct();
            foreach (var info in values)
            {
                _context.AddAddressableBundle(info.assetPaths, info.key);
            }
            _atlasInfoMap.Clear();
        }
    }
}
