using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PanelMgr
{
    private static PanelMgr mInstance;
    public static PanelMgr instance
    {
        get
        {
            if (null == mInstance)
                mInstance = new PanelMgr();
            return mInstance;
        }
    }

    // 根目录canvas
    private Transform mRootCanvas;

    // 界面管理仓库
    private Dictionary<string, BasePanel> mPanels = new Dictionary<string, BasePanel>();

    public void Init()
    {
        mRootCanvas = GameObject.Find("Canvas").transform;
    }

    /// <summary>
    /// 展示界面
    /// </summary>
    /// <param name="panelName">界面名称</param>
    /// <param name="resId">资源id</param>
    /// <returns></returns>
    public BasePanel ShowPanel(string panelName, int resId)
    {
        if (null != panelName && mPanels.ContainsKey(panelName))
            return mPanels[panelName];
        var resCfg = ResourceCfg.instance.GetResCfg(resId);
        if (null != resCfg)
        {
            return ShowPanel<BasePanel>(panelName, resCfg.editor_path);
        }
        else
        {
            GameLogger.LogError("ShowPanel Error, null == resCfg, resId = " + resId);
            return null;
        }
    }

    public T ShowPanel<T>(string panelName, string resPath) where T : BasePanel
    {
        if (null != panelName && mPanels.ContainsKey(panelName))
            return mPanels[panelName] as T;
        var prefab = ResourceMgr.instance.LoadAsset<GameObject>(resPath);
        var go = Object.Instantiate(prefab);
        go.transform.SetParent(mRootCanvas, false);
        var panel = go.GetOrAddComponent<T>();
        panel.Initialize(panelName, go);
        if (null != panelName)
            mPanels.Add(panelName, panel);
        panel.Show();
        return panel;
    }

    public GameObject InstantiateUI(int resId)
    {
        var resCfg = ResourceCfg.instance.GetResCfg(resId);
        if (null == resCfg)
        {
            return null;
        }
        var prefab = ResourceMgr.instance.LoadAsset<GameObject>(resCfg.editor_path);
        if (null == prefab)
            return null;
        var uiObj = Object.Instantiate(prefab);
        uiObj.transform.SetParent(mRootCanvas, false);
        return uiObj;
    }
    public void HidePanel(string panelName)
    {
        if (mPanels.ContainsKey(panelName))
        {
            mPanels[panelName].Hide();
            mPanels.Remove(panelName);
        }
    }

    public void HideAllPanels()
    {
        foreach(var panel in mPanels.Values)
        {
            panel.Hide();
        }
        mPanels.Clear();
    }
}
