using XGame.Framework.Asyncs;
using UnityEngine;

namespace XGame.Framework.Asset
{
    internal class AssetBundleCreateRequestAsync : Async, IAssetAsync
    {
        private AssetBundleCreateRequest request;
        public string Path { get; internal set; }
        public uint Offset { get; internal set; }
        /// <summary>
        /// 此处先存bundleName
        /// </summary>
        public string AddressableName { get; internal set; }
        public override float Progress
        {
            get => request != null ? request.progress : 0;
            protected set => base.Progress = value;
        }

        public void Start()
        {
            //Log.Warn($"AssetBundleCreateRequestAsync Start. Path:{Path}");
            request = Offset > 0 ?  AssetBundle.LoadFromFileAsync(Path, 0, Offset) : AssetBundle.LoadFromFileAsync(Path);
            request.completed += OnCompleted;
        }
        void OnCompleted(AsyncOperation async)
        {
            if (!async.isDone || request.assetBundle == null)
                AssetsLog.Warn("{0} is not a valid bundle. name:{1} instance:{2}", Path, AddressableName, request.assetBundle?.GetInstanceID());
            Completed();
        }

        public object GetResult()
        {
            object result = null;
            if (request != null)
            {
                //Log.Warn($"AssetBundleCreateRequestAsync Get bundle:{request.assetBundle? .GetInstanceID()??0} Path:{Path}");
                result = request.assetBundle;
            }
            Clear();
            return result;
        }
        void Clear()
        {
            request = null;
        }
    }
}


