using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace XGame.Framework.Asset
{
    /// <summary>
    /// 已加载资源的仓库
    /// </summary>
    internal class AssetRepository
    {
        AssetRecycler Recycler { set; get; }
        /// <summary>
        /// 资源缓存容器
        /// </summary>
        Dictionary<string, Asset> AssetMap { set; get; }
        /// <summary>
        /// 所有从仓库拿出去的对象的hashcode容器
        /// </summary>
        Dictionary<long, string> UsingHashCodes { set; get; }

        public AssetRepository()
        {
            Recycler = new AssetRecycler();
            AssetMap = new Dictionary<string, Asset>();
            UsingHashCodes = new Dictionary<long, string>();
        }
        #region Asset
        public bool ContainsAsset(string addressableName)
        {
            return AssetMap.ContainsKey(addressableName);
        }
        public void AddAsset(Asset asset)
        {
            //Assert.IsNotNull(asset);
            if (asset == null)
            {
                AssetsLog.Warn("Repository Add Invalid Asset.");
                return;
            }
            var assetName = asset.AddressableName;
            if (AssetMap.ContainsKey(assetName))
            {
                AssetsLog.Warn($"Asset Repeat:{assetName}  current:{AssetMap[assetName].Source.GetLongHashCode()}  next:{asset.Source.GetLongHashCode()}");
                return;
            }
            AssetMap.Add(assetName, asset);
        }

        public Asset GetAsset(string addressableName)
        {
            AssetMap.TryGetValue(addressableName, out Asset asset);
            return asset;
        }
        public void RemoveAsset(string addressableName)
        {
            AssetMap.Remove(addressableName);
        }
        #endregion
        /// <summary>
        /// 克隆对象
        /// </summary>
        /// <param name="addressableName"></param>
        /// <returns></returns>
        public object Clone(string addressableName)
        {
            var result = Recycler.Pop(addressableName);
            if (result != null)
            {
                return result;
            }
            result = GetAsset(addressableName)?.Clone();
            if (result != null)
            {
                Regist(result.GetLongHashCode(), addressableName);
            }
            return result;
        }
        /// <summary>
        /// 回收对象
        /// </summary>
        /// <param name="obj"></param>
        public void Recycle(object obj)
        {
            if (obj is RecycleObject recycleObject)
            {
                if (recycleObject.asset == null || recycleObject.asset as Object == null)
                {
                    //GameObject被销毁后,System.object对象判断还是非空，只能通过UnityEngine.Object来判断非空
                    //资源被业务销毁了
                    var hashcode = recycleObject.hashcode;
                    var assetName = GetNameByHashCode(hashcode);
                    if (!string.IsNullOrEmpty(assetName))
                    {
                        var asset = GetAsset(assetName);
                        if (asset != null)
                        { //通过loader加载的资源
                            if (asset.IsCloneable)
                            {
                                asset.Release();
                                UnRegist(hashcode);
                            }
                            else
                            {
                                for (var i = 0; i < recycleObject.reference; i++)
                                {
                                    if (asset.Release())
                                    {
                                        // 预留引用归零时的处理
                                        UnRegist(hashcode);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    InternalRecycle(recycleObject.asset, recycleObject.reference, recycleObject.destroyImmediate);
                }
            }
            else
            {
                InternalRecycle(obj, 1, false);
            }
        }
        /// <summary>
        /// 回收对象
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="reference"></param>
        /// <param name="destroyImmediate"></param>
        private void InternalRecycle(object obj, int reference, bool destroyImmediate)
        {
            if (obj == null || obj as Object == null) return;
            if (obj is Component component && component != null)
            {
                obj = component.gameObject;
            }
            else if (obj is Sprite sprite && sprite != null)
            {
                if (!string.IsNullOrEmpty(GetNameByObject(sprite.texture)))
                { //如果这里记录的是Texture，则将Sprite转为Texture处理
                    obj = sprite.texture;
                }
            }
            var assetName = GetNameByObject(obj);
            if (!string.IsNullOrEmpty(assetName))
            {
                var asset = GetAsset(assetName);
                if (asset != null)
                { //通过loader加载的资源
                    if (asset.IsCloneable)
                    {
                        if (destroyImmediate && obj is GameObject destroyGo)
                        {//需要销毁的GameObject
                            for (var i = 0; i < reference; i++)
                            {
                                if (asset.Release())
                                {
                                    // 预留引用归零时的处理
                                    UnRegist(destroyGo.GetLongHashCode());
                                }
                            }
                            Object.Destroy(destroyGo);
                            return;
                        }
                        Recycler.Push(obj, assetName);
                    }
                    else
                    {
                        for (var i = 0; i < reference; i++)
                        {
                            if (asset.Release())
                            {
                                // 预留引用归零时的处理
                                UnRegist(obj.GetLongHashCode());
                            }
                        }
                    }
                    return;
                }
            }
            //执行销毁
            if (obj is GameObject gameObject)
            {
                Object.Destroy(gameObject);
            }
        }

        public void UnloadUnusedAssets(System.Action<string, object> onUnload)
        {
            List<Asset> unloadAssets = new List<Asset>();
            foreach (var item in AssetMap)
            {
                int reference = item.Value.Reference;
                if (item.Value.IsPreload == false && (reference <= 0 || reference == Recycler.GetCount(item.Key)))
                { //非预加载 并且 没有引用或者引用全在Recycler里
                    unloadAssets.Add(item.Value);
                }
            }
            foreach (var asset in unloadAssets)
            {
                var assetName = asset.AddressableName;
                //recycle销毁Asset的实例对象
                Recycler.Destroy(assetName, UnRegist);
                AssetMap.Remove(assetName);
                //这里不直接Dispose Asset，只是返回给Loader
                onUnload?.Invoke(assetName, asset.Source);
            }
            unloadAssets.Clear();
        }
        public void SetPreloadSign(string addressableName, bool isPreload)
        {
            var asset = GetAsset(addressableName);
            if (asset == null)
            {
                return;
            }
            if (asset.Reference > 0)
            { // 引用计数大于零，不能设置为预加载
                isPreload = false;
            }
            asset.IsPreload = isPreload;
        }
        public void Dispose()
        {
            //先清理回收站
            Recycler.Dispose();
            //释放Asset后才能释放AssetBundle
            var assets = AssetMap.Values.ToList();
            assets.Sort((a, b) => a.AssetType - b.AssetType);
            foreach (var it in assets)
            {
                it.Dispose();
            }
            assets.Clear();
            AssetMap.Clear();
            UsingHashCodes.Clear();
        }
        #region 内部函数
        // ReSharper disable once IdentifierTypo
        // ReSharper disable once ArrangeTypeMemberModifiers
        private void Regist(long hashCode, string addressableName)
        {
            if (!UsingHashCodes.ContainsKey(hashCode))
            {
                UsingHashCodes.Add(hashCode, addressableName);
            }
            else if (!addressableName.Equals(UsingHashCodes[hashCode]))
            {
                AssetsLog.Error($"Asset hash repeat. Hash:{hashCode} Last:{UsingHashCodes[hashCode]} Next:{addressableName}");
            }
        }
        // ReSharper disable once IdentifierTypo
        private void UnRegist(long hashCode)
        {
            if (UsingHashCodes.ContainsKey(hashCode))
            {
                UsingHashCodes.Remove(hashCode);
            }
        }
        private string GetNameByHashCode(long hashCode)
        {
            UsingHashCodes.TryGetValue(hashCode, out var addressableName);
            return addressableName;
        }
        private string GetNameByObject(object obj)
        {
            UsingHashCodes.TryGetValue(obj?.GetLongHashCode() ?? 0, out var addressableName);
            return addressableName;
        }
        #endregion
    }
}

