using System.Collections.Generic;

namespace XGame.Framework.Asset
{
    /// <summary>
    /// 加载过的资源对象，只用于内部记录引用
    /// </summary>
    internal class AssetInstance
    {
        public object Asset { private set; get; }
        public int Reference { private set; get; }
        public long Hashcode { private set; get; }
        public string Name { private set; get; }
        private List<long> parents;
        public AssetInstance(object asset, string name)
        {
            Asset = asset;
            Reference = 1;
            Hashcode = asset.GetLongHashCode();
            Name = name;
        }
        public void Retain()
        {
            Reference++;
        }
        public bool Release()
        {
            return --Reference <= 0;
        }

        public bool AddParent(long parentHash)
        {
            if (parents == null)
            {
                parents = new List<long>();
            }

            if (parents.Contains(parentHash))
            {
                return false;
            }

            parents.Add(parentHash);
            return true;
        }

        public bool RemoveParent(long parentHash)
        {
            return parents?.Remove(parentHash) ?? false;
        }

        public bool IsContainParent(long parentHash)
        {
            return parents?.Contains(parentHash) ?? false;
        }
        public override string ToString()
        {
            return $"LoadedAsset type:{Asset?.GetType()} name:{Name} hash:{Hashcode} ref:{Reference}";
        }

        public void Clear()
        {
            Asset = null;
            Reference = 0;
            Hashcode = 0;
            Name = string.Empty;
            parents?.Clear();
        }
        internal AssetInstance Clone()
        {
            var clone = new AssetInstance(Asset, Name)
            {
                Reference = Reference,
            };
            return clone;
        }
    }
}
