using XGame.Framework.Asset.Addressable;
using System;
using System.IO;
using UnityEngine;
using Object = UnityEngine.Object;

namespace XGame.Framework.Asset
{
    internal class ResourcesLoader : BaseLoader, IAssetLoader
    {
        private IAddressableManifest _addressableManifest;
        public ResourcesLoader(IAddressableManifest addressableManifest)
        {
            _addressableManifest = addressableManifest;
        }
        public IAssetAsync LoadAsync<TResult>(string addressableName)
        {
            return GetAssetAsync(addressableName);
        }

        public object LoadSync<TResult>(string addressableName)
        {
            //int rootIndex = addressableName.IndexOf("Resources/", StringComparison.Ordinal);
            //string path = rootIndex != -1 ? addressableName.Substring(rootIndex + 10) : addressableName;
            //if (Path.HasExtension(path))
            //{
            //    path = path.Substring(0, path.LastIndexOf('.'));
            //}
            return Resources.Load(GetPathByName(addressableName));
        }

        public IAssetAsync LoadSceneBundleAsync(string sceneName)
        {
            throw new System.NotImplementedException();
        }

        public void UnLoadSceneBundle(string sceneName)
        {
            throw new System.NotImplementedException();
        }

        public void Unload(string assetPath, object source)
        {
            if (source is Object obj)
            {
                obj.Unload();
                //Resources.UnloadAsset(obj);
            }
        }
        public void UnloadUnusedAssets()
        {
            //throw new System.NotImplementedException();
        }

        protected override void OnDispose()
        {
            _addressableManifest = null;
        }

        private string GetPathByName(string addressableName)
        {
            var relativePath = _addressableManifest.GetRelativePath(addressableName);
            if (string.IsNullOrEmpty(relativePath))
            {
                AssetsLog.Error($"Resources Loader can't find relativePath. Name:{addressableName}");
            }
            return relativePath;
        }
        private IAssetAsync GetAssetAsync(string addressableName)
        {
            var assetAsync = AsyncPool.GetAssetAsync(addressableName);
            if (assetAsync == null)
            {
                var async = new ResourcesAsync()
                {
                    AddressableName = addressableName,
                    Path = GetPathByName(addressableName)
                };
                assetAsync = async;
                AsyncPool.AddAsync(assetAsync);
            }
            return assetAsync;
        }
    }
}

