using UnityEngine;
using XGame.Framework.Asset;
using XGame.Framework.Asyncs;

namespace XGame.Framework.Shaders
{
    /// <summary>
    /// shader变体预热
    /// ShaderVariantCollection
    /// </summary>
    internal class ShaderCollectionAsync : Async
    {
        private IAssetLoadAsync<ShaderVariantCollection> _async;
        public ShaderCollectionAsync(string addressableName)
        {
            if (string.IsNullOrEmpty(addressableName))
            {
                Log.Error("ShaderCollectionAsync Name is null.");
                Completed();
                return;
            }

            Log.Info($"ShaderCollectionAsync start. Name:{addressableName}");
            _async = AssetManager.LoadAsync<ShaderVariantCollection>(addressableName);
            _async.On(OnLoaded);
        }
        private void OnLoaded(IAsync async)
        {
            _async = null;
            var result = async as IAssetLoadAsync<ShaderVariantCollection>;
            var collection = result?.Result;
            Log.Info($"ShaderCollectionAsync result:{collection != null} isWarmedUp:{collection?.isWarmedUp ?? false}");

            collection?.WarmUp();
            Completed();
            if (collection)
            {
                AssetManager.Recycle(collection);
            }
            Log.Info("ShaderCollectionAsync completed.");
        }
        protected override void OnRemoveAll()
        {
            _async?.RemoveOn(OnLoaded);
            _async = null;
        }
    }
}
