
using XGame.Framework.Asyncs;

namespace XGame.Framework.Asset
{
    internal class SceneLoadAsync : Async, IAssetAsync
    {

        public string AddressableName { get; internal set; }
        /// <summary>
        /// async的Start标记
        /// </summary>
        private bool isStart;
        /// <summary>
        /// asyncGroup完成标记
        /// </summary>
        private bool groupCompleted;
        /// <summary>
        /// scene所依赖的bundle的AsyncGroup
        /// </summary>
        private AsyncGroup bundleAsyncGroup;
        internal AsyncGroup BundleAsyncGroup
        {
            get => bundleAsyncGroup;
            set
            {
                bundleAsyncGroup = value;
                bundleAsyncGroup?.On(OnGroupCompleted);
            }
        }

        public int AssetHash { get; set; }

        public override float Progress
        {
            get {
                float progress = bundleAsyncGroup?.Progress ?? 0;
                return progress / 2;
            }
            protected set => base.Progress = value;
        }

        public object GetResult()
        {
            return null;
        }

        public void Start()
        {
            isStart = true;
            if(bundleAsyncGroup == null || groupCompleted)
            {
                Completed();
            }
        }

        private void OnGroupCompleted(IAsync async)
        {
            groupCompleted = true;
            if (isStart)
            {
                Completed();
            }
        }

        private void Clear()
        {
            isStart = false;
            groupCompleted = false;
            bundleAsyncGroup = null;
        }
    }
}
