using FairyGUI;
using UnityEngine;

namespace ET.Client
{
    public static class UIHelper
    {
        public static async ETTask<GComponent> Create(string packName, string uiName = null)
        {
            var ass = await YooAssetProxy.LoadAssetAsync<TextAsset>($"FGUI_{packName}_fui");
            UIPackage.AddPackage(ass.GetAssetObject<TextAsset>().bytes, packName, LoadPackageInternalAsync);
            var view = UIPackage.CreateObject(packName, uiName ?? packName).asCom;
            view.name = uiName ?? packName;
            GRoot.inst.AddChild(view);
            return view;
        }

        private static async void LoadPackageInternalAsync(string name, string extension, System.Type type, PackageItem item)
        {
            var tex = await YooAssetProxy.LoadAssetAsync<Texture>($"FGUI_{name}");
            item.owner.SetItemAsset(item, tex.GetAsset<Texture>(), DestroyMethod.Unload);
        }

        public static bool Remove(string uiName, bool release = true)
        {
            var view = GRoot.inst.GetChild(uiName);
            if (view != null)
            {
                GRoot.inst.RemoveChild(view, release);
                return true;
            }
            return false;
        }

        public static bool SetVisible(string uiName, bool flag)
        {
            var view = GRoot.inst.GetChild(uiName);
            if (view != null)
            {
                view.visible = flag;
                return true;
            }
            return false;
        }

        public static GObject GetUI(string uiName)
        {
            return GRoot.inst.GetChild(uiName);
        }
    }
}