using System;
using System.Collections;

using UnityEngine;


namespace Giant.Res {

    public enum LoadState
    {
        Init,
        LoadAssetBundle,
        LoadAsset,
        Instance,
        Loaded,
        Unload,
    }

    public class Ref
    {
        public int refCount;

        public bool IsUnused() {
            return refCount <= 0;
        }

        public void Retain()
        {
            refCount++;
        }

        public virtual void Release()
        {
            refCount--;
        }
    }
    public class AssetRequest : Ref, IEnumerator
    {
        public Type assetType;
        public string path;

        public LoadState loadState { get; protected set; }
        public bool error { get; protected set; }

        public virtual float progress { get; }

        public AssetRequest()
        {
            asset = null;
            loadState = LoadState.Init;
            error = false;
        }
        public virtual bool isDone
        {
            get { return true; }
        }

        public Action<AssetRequest> completed;

        public UnityEngine.Object asset { get; internal set; }

        internal virtual void Load()
        {
            if (!AssetsMgr.UseAssetBundle && AssetsMgr.loadDelegate != null)
            {
                asset = AssetsMgr.loadDelegate(path, assetType);//AssetDatabase.LoadAssetAtPath(assetpath, assetType);
            }
            if (asset == null)
            {
                error = true;
                Debug.LogError("file not exist:" + path);
            }
        }

        internal virtual void Unload()
        {
            if (asset == null)
                return;

            //if (!AssetsMgr.UseAssetBundle)
            //{
            //    if (!(asset is GameObject))
            //    {
            //        Resources.UnloadAsset(asset);
            //    }
            //}

            asset = null;
        }

        internal bool Update()
        {
            if (!isDone)
                return true;

            if (completed == null)
                return false;

            try
            {
                completed.Invoke(this);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
            }
            completed = null;
            return false;
        }


        public object Current => null;

        public bool MoveNext()
        {
            return !isDone;
        }

        public void Reset()
        {

        }
    }



}