﻿using System;
using System.Collections;
using UnityEngine;
using Object = UnityEngine.Object;

namespace JLGames.RocketDriver.Actions.Loaderx
{
    internal sealed class ResLoader : LoaderBase, ILoader
    {
        internal ResLoader()
        {
            m_BaseInfo = new LoaderBaseInfo();
            m_BundleLoader = new ResBundleLoader();
            m_AssetLoader = new ResAssetLoader(m_BaseInfo);
        }

        public void InitLoader(LoaderSettings settings)
        {
            m_OriginalSettings = settings;
            var sr = settings.DefaultResourceSetting;
            if ("" != sr.ProjectBasePath)
            {
                SetBaseUri("", sr.ProjectBasePath);
            }
        }

        /// <summary>
        /// BaseReqUri will be ignored in Resources Mode.
        /// </summary>
        /// <param name="baseReqUri"></param>
        /// <param name="baseLocUri"></param>
        /// <exception cref="Exception"></exception>
        public void SetBaseUri(string baseReqUri, string baseLocUri)
        {
            Debug.Log("BaseReqUri will be ignored in Resources Mode.");
            m_BaseInfo.SetBaseLocUri(baseLocUri);
        }

        public void SetCacheSetting(string cacheName, string cachePath)
        {
        }

        //多层异步资源加载------------------------------------------------------------

        public IEnumerator LoadAssetAsync<T>(string bundleName, string assetPath,
            LoaderDelegate.OnAssetWithBundleLoaded<T> onLoaded,
            bool autoRelease = true, bool unloadObjects = false) where T : Object
        {
            if (string.IsNullOrEmpty(bundleName) || string.IsNullOrEmpty(assetPath))
            {
                throw LoaderErrors.ErrorNameEmpty;
            }

            var req = Resources.LoadAsync<T>(assetPath);
            yield return req;
            if (req.isDone && req.asset != null)
            {
                Internal.ApplyAssetWithBundleCallback(onLoaded, null, req.asset as T, true);
            }
            else
            {
                Internal.ApplyAssetWithBundleCallback(onLoaded, null, null, false);
            }
        }
    }
}