using System.Collections.Generic;
using UnityEditor;
using XGame.Framework;

namespace XGame.Editor.Build.AssetBundles
{
    public class SceneBundleCollector
    {
        public Dictionary<long, AssetBundleData> bundleBuildMap;
        private BundleContext _context;
        public SceneBundleCollector(BundleContext context)
        {
            _context = context;
            bundleBuildMap = new Dictionary<long, AssetBundleData>();
        }

        /// <summary>
        /// 收集scene的bundle信息
        /// </summary>
        /// <param name="assetBundleBuilds">bundle信息集合</param>
        /// <returns></returns>
        public bool Collect()
        {
            var sceneNames = new HashSet<string>();
            var xgameConfig = XGameConfig.Load();
            var launchScene = xgameConfig.launchSceneName.ToLower();
            // 遍历所有场景
            for (int i = 0, len = EditorBuildSettings.scenes.Length; i < len; ++i)
            {
                var editorScene = EditorBuildSettings.scenes[i];
                if (!editorScene.enabled)
                {
                    continue;
                }
                var sceneName = System.IO.Path.GetFileNameWithoutExtension(editorScene.path).ToLower();
                // 判断是否有同名scene
                if (sceneNames.Contains(sceneName))
                {
                    BuildLog.Error($"有相同名字的Scene:{sceneName}");
                    return false;
                }
                sceneNames.Add(sceneName);
                // Launch场景不打assetBundle,build Setting中enable的场景打包
                if (sceneName != launchScene)
                {
                    AddSceneBundle(editorScene.path);
                }
            }
            sceneNames.Clear();
            return true;
        }
        private void AddSceneBundle(string scenePath)
        {
            var bundle = _context.AddRawAssetBundle(new string[] { scenePath }, AssetDatabase.AssetPathToGUID(scenePath), false);
            bundleBuildMap.Add(bundle.bundleId, bundle);
        }
        //private AssetBundleData CreateBundleBuild(string scenePath, string sceneName, string bundleName = null)
        //{
        //    if (string.IsNullOrEmpty(bundleName))
        //    {
        //        var tempBundleName = scenePath.Remove(scenePath.Length - 6).Replace('/', '_').ToLower();
        //        bundleName = $"scene_{tempBundleName}";
        //    }

        //    var assetNames = new string[] { scenePath };
        //    var addreNames = new string[] { scenePath };

        //    AssetBundleData assetBundleBuild = new AssetBundleData(bundleName, Define.BUNDLE_VARIANT, assetNames, addreNames);
        //    return assetBundleBuild;
        //}
    }
}
