using XGame.Framework.Asyncs;
using UnityEngine;

namespace XGame.Framework.Asset
{
    internal class ResourcesAsync : Async, IAssetAsync
    {
        public string Path { get; internal set; }
        public string AddressableName { get; internal set; }
        ResourceRequest request;

        public override float Progress
        {
            get => request?.progress ?? 0;
            protected set => base.Progress = value;
        }

        public object GetResult()
        {
            object result = null;
            if (request != null)
                result = request.asset;
            Clear();
            return result;
        }

        public void Start()
        {
            //int rootIndex = Path.IndexOf("Resources/", StringComparison.Ordinal);
            //string path = rootIndex != -1 ? Path.Substring(rootIndex + 10) : Path;
            //if (System.IO.Path.HasExtension(path))
            //{
            //    path = path.Substring(0, path.LastIndexOf('.'));
            //}
            request = Resources.LoadAsync(Path);
            request.completed += OnCompleted;
        }

        void OnCompleted(AsyncOperation async)
        {
            if (!async.isDone || request.asset == null)
                AssetsLog.Error($"{Path} is not a valid asset. name:{AddressableName} instance:{request.asset?.GetInstanceID()}");
            Completed();
        }
        void Clear()
        {
            request = null;
        }
    }
}