using System;
using UnityEngine;
using XGame.Framework.Asset;

namespace XGame.Framework.UI
{
    internal class UIAssetModule : IUIAssetModule, IDisposable
    {
        private IAssetModule _assetModule;
        private UIContext _context;

        public UIAssetModule(UIContext context)
        {
            _context = context;
            _assetModule = new AssetModule();
        }

        IAssetLoadAsync<TResult> IUIAssetModule.LoadAsync<TResult>(string addressableName)
        {
            return _assetModule.LoadAsync<TResult>(addressableName);
        }
        void IUIAssetModule.Recycle(UnityEngine.Object obj, bool isDestroy)
        {
            if (obj is GameObject go)
            {
                _assetModule.Recycle(go, isDestroy);
            }
            else
            {
                _assetModule.Recycle(obj);
            }
        }
        IAssetLoadAsync<INestedView> IUIAssetModule.LoadNested(UIKey nestedKey)
        {
            var loadAsync = _assetModule.LoadAsync<UINested>(nestedKey.Key);
            var nestedAsync = new UINestedLoadAsync(loadAsync, nestedKey, null, _context);
            return nestedAsync;
        }
        void IUIAssetModule.Recycle(INestedView nestedView, bool isDestroy)
        {
            if (nestedView == null) return;
            nestedView.Disable();
            var nested = (nestedView as INestedInternal)?.Nested;
            (nestedView as IDisposable)?.Dispose();
            if (nested is UINested uiNested)
            {
                _assetModule.Recycle(uiNested.gameObject, isDestroy);
            }
        }

        void IUIAssetModule.StopAllAsyncs()
        {
            _assetModule.StopAllAsyncs();
        }

        //void IUIAssetModule.UnloadUnusedAssets()
        //{
        //    _assetModule.UnloadUnusedAssets();
        //}

        void IDisposable.Dispose()
        {
            (_assetModule as IDisposable)?.Dispose();
            _assetModule = null;
            _context = null;
        }
    }
}
