using System.Collections.Generic;
using UnityEditor;

namespace XGame.Editor.Build.AssetBundles
{
    public class ShaderBundleCollector
    {
        private BundleContext _context;
        public ShaderBundleCollector(BundleContext context)
        {
            _context = context;
        }
        public void Collect()
        {
            if (_context.isMergeShader == false)
            {
                return;
            }
            var assetsRoots = _context.assetsRoots;
            for (var index = 0; index < assetsRoots.Length; index++)
            {
                //按照资源根目录("Assets/Presource/"优先)来分ShaderVariant和shader的ab包
                var guids = AssetDatabase.FindAssets("t:ShaderVariantCollection", new string[] { assetsRoots[index] });
                if (guids == null || guids.Length == 0)
                    continue;
                var assetPaths = new List<string>();
                foreach (var guid in guids)
                {
                    var variantPath = AssetDatabase.GUIDToAssetPath(guid);
                    if (_context.bundleAssetPaths.Contains(variantPath))
                    {
                        continue;
                    }
                    assetPaths.Add(variantPath);
                }
                string[] variantPaths = assetPaths.ToArray();
                var dependencies = AssetDatabase.GetDependencies(variantPaths);
                System.Array.Sort(dependencies, (a, b) => string.Compare(a, b, System.StringComparison.OrdinalIgnoreCase));
                foreach (var dep in dependencies)
                {
                    if (_context.bundleAssetPaths.Contains(dep) ||
                        dep.EndsWith(_context.ShaderExt, System.StringComparison.OrdinalIgnoreCase) == false)
                    {
                        continue;
                    }
                    assetPaths.Add(dep);
                }
                
                _context.AddAddressableBundle(assetPaths.ToArray(), guids[0]);
            }

        }
    }
}
