
using System;
using UnityEngine;

namespace Giant.Res {

    public class BundleAssetAsyncRequest : BundleAssetRequest
    {

        private AssetBundleRequest _request;
        public BundleAssetAsyncRequest(string bundle) :
            base(bundle)
        {

        }

        public override bool isDone
        {
            get
            {
                //已经卸载了
                if(loadState == LoadState.Unload)
                {
                    return true;
                }
               
                if (error || bundle.error)
                    return true;

                for (int i = 0; i < bundle.dependencies.Count; i++) {
                    var item = bundle.dependencies[i];
                    if (item.error)
                        return true;
                }

                switch (loadState)
                {
                    case LoadState.Init:
                        return false;
                    case LoadState.Loaded:
                        return true;
                    case LoadState.LoadAssetBundle:
                        {
                            if (!bundle.isDone)
                                return false;

                            for (int i = 0; i < bundle.dependencies.Count; i++)
                            {
                                var item = bundle.dependencies[i];
                                if (!item.isDone)
                                {
                                    return false;
                                }
                            }

                            if (bundle.assetBundle == null)
                            {
                                error = true;
                                return true;
                            }

                            var assetName = path;//Path.GetFileName(path);
                            _request = bundle.assetBundle.LoadAssetAsync(assetName, assetType);
                            loadState = LoadState.LoadAsset;
                            break;
                        }
                    case LoadState.Unload:
                        return true;
                    case LoadState.LoadAsset:
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                if (loadState != LoadState.LoadAsset)
                    return false;
                if (!_request.isDone)
                    return false;

                asset = _request.asset;
                loadState = LoadState.Loaded;
                return true;
            }
        }

        internal override void Load()
        {
            bundle = AssetsMgr.LoadBundleAsync(assetBundleName);
            loadState = LoadState.LoadAssetBundle;
        }

        internal override void Unload()
        {
            _request = null;
            loadState = LoadState.Unload;
            base.Unload();
        }
    }
}