using FairyGUI;
using UnityEngine;

namespace ET.Client
{
    public static class UIHelper
    {
        public static async ETTask<GComponent> Create(string packName, string uiName = null, int index = -1, GComponent parent = 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;

            if(parent == null)
            {
                parent = GRoot.inst;
            }
            if (index >= 0)
            {
                parent.AddChildAt(view, index);
            }
            else
            {
                parent.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);
        }

        public static async void ShowLoadingUI()
        {
            var loading = UIHelper.GetUI("Loading");
            if (loading == null)
            {
                await UIHelper.Create("Loading");
            }
            else
            {
                loading.visible = true;
            }
        }
        public static void HideLoadingUI()
        {
            SetVisible("Loading", false);
        }
    }
}