using XGame.Editor.Asset;
using XGame.Framework.Asset;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace XGame.Editor.Build.AssetBundles
{
    internal class SceneManifestController
    {
        private SceneBundleCollector _sceneCollector;
        public SceneManifestController(SceneBundleCollector sceneCollector)
        {
            //_context = context;
            _sceneCollector = sceneCollector;
        }
        public bool GenerateManifest()
        {
            string sceneAssetBundleManifestPath = PathDefine.SceneAssetBundleManifestPath;//"Assets/KCAssetBundlesData/KCSceneAssetBundleManifest.asset";
            var sceneInfosSo = AssetDatabase.LoadAssetAtPath<SceneInfosSo>(sceneAssetBundleManifestPath);
            if (sceneInfosSo == null)
            {
                sceneInfosSo = ScriptableObject.CreateInstance<SceneInfosSo>();
                AssetDatabase.CreateAsset(sceneInfosSo, sceneAssetBundleManifestPath);
            }
            //bundle信息
            var sceneInfos = new List<SceneAssetInfo>();
            if (_sceneCollector.bundleBuildMap.Count > 0)
            {
                foreach (var keyValue in _sceneCollector.bundleBuildMap)
                {
                    foreach (var assetName in keyValue.Value.assetNames)
                    {
                        var assetInfo = new SceneAssetInfo()
                        {
                            sceneName = System.IO.Path.GetFileNameWithoutExtension(assetName).ToLower(),
                            assetName = assetName
                        };
                        sceneInfos.Add(assetInfo);
                    }
                }
                //排序
                sceneInfos.Sort((a, b) => { return string.CompareOrdinal(a.assetName, b.assetName); });
            }
            //保存
            sceneInfosSo.sceneInfos = sceneInfos.ToArray();
            EditorUtility.SetDirty(sceneInfosSo);
            AssetDatabase.SaveAssets();
            BuildLog.Log("Save SceneBundleManifest.");
            AssetDatabase.Refresh();
            return true;
        }
    }
}
