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

namespace XGame.Framework.FGUI
{
    internal class FguiAssetModule : IUIAssetModule, IDisposable
    {
        private IAssetModule _assetModule;
        private IAssetModule Asset => _assetModule ?? (_assetModule = new AssetModule());
        private UIContext _context;
        private IPackageHandle _pkgHandle;
        public FguiAssetModule(UIContext context, IPackageHandle pkgHandle)
        {
            _context = context;
            _pkgHandle = pkgHandle;
        }
        IAssetLoadAsync<TResult> IUIAssetModule.LoadAsync<TResult>(string addressableName)
        {
            return Asset.LoadAsync<TResult>(addressableName);
        }
        void IUIAssetModule.Recycle(UnityEngine.Object obj, bool isDestroy)
        {
            if (obj is GameObject go)
            {
                Asset.Recycle(go, isDestroy);
            }
            else
            {
                Asset.Recycle(obj);
            }
        }
        IAssetLoadAsync<INestedView> IUIAssetModule.LoadNested(UIKey nestedKey)
        {
            return LoadNested(nestedKey, null);
        }
        /// <summary>
        /// fgui全部销毁
        /// </summary>
        /// <param name="nestedView"></param>
        /// <param name="isDestroy"></param>
        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 FguiNested uiNested)
            {
                var com = uiNested.Component;
                com.parent?.RemoveChild(com);
                com.Dispose();
            }
        }
        void IUIAssetModule.StopAllAsyncs()
        {
            _assetModule?.StopAllAsyncs();
        }
        void IDisposable.Dispose()
        {
            (_assetModule as IDisposable)?.Dispose();
            _assetModule = null;
            _context = null;
            _pkgHandle = null;
        }

        public IAssetLoadAsync<INestedView> LoadNested(UIKey nestedKey, GComponent parent)
        {
            var objLoadAsync = _pkgHandle.LoadGobjectAsync(nestedKey);
            var nestedLoadAsync = new FguiNestedLoadAsync(objLoadAsync, nestedKey, parent, _context);
            return nestedLoadAsync;
        }
    }
}
