using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;
using EditorFramework;
using UnityEngine.SceneManagement;

namespace Stary.Evo.Editor
{
    /// <summary>
    /// 设置字体面板
    /// </summary>
    public class DefaultFontEditor : IFontChange
    {
        private static Font m_font;

        public void Creat()
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("选择默认字体");
            EditorGUILayout.Space();
            m_font = (Font) EditorGUILayout.ObjectField(m_font, typeof(Font), true,GUILayout.MinWidth(100f),GUILayout.MinHeight(30));
            EditorGUILayout.Space();
            GUI.color = Color.green;
            if (GUILayout.Button("确定",GUILayout.MinWidth(200), GUILayout.MinHeight(50)))
            {
                ToolCacheManager.SaveFont(m_font);
            }
        }
        [MenuItem("GameObject/UI/DefaultText")]
        static void CreatImage()
        {
            Text text = CreateComponent<Text>();
            if (text!=null)
            {
                text.font = ToolCacheManager.GetFont();
            }
        }
        private static T CreateComponent<T>() where T : Component
        {
            string name = typeof(T).Name;
            GameObject go = new GameObject(name);
            Transform parent = GetUIParent();
            go.transform.SetParent(parent, false);
            T com = go.AddComponent<T>();
            return com;
        }
        private static Transform GetUIParent()
        {
            Transform select = Selection.activeTransform;
            if (select)
            {
                if (select.GetComponentInParent<Canvas>())
                {
                    return select;
                }
                else
                {
                    Canvas canvas = select.GetComponentInChildren<Canvas>();
                    if (canvas == null)
                    {
                        canvas = InstanceCanvas(select);
                    }
                    return canvas.transform;
                }
            }
            else
            {
                Canvas canvas = GetCanvasInScene();
                if (canvas == null)
                {
                    canvas = InstanceCanvas();
                }
                return canvas.transform;
            }
        }
        /// <summary>
        /// 参考PrefabStageUtility.HandleUIReparentingIfNeeded
        /// </summary>
        /// <returns></returns>
        static Canvas GetCanvasInScene()
        {
            Scene scene = SceneManager.GetActiveScene();
            foreach (GameObject go in scene.GetRootGameObjects())
            {
                var canvas = go.GetComponentInChildren<Canvas>();
                if (canvas != null)
                    return canvas;
            }
            return null;
        }
        /// <summary>
        /// 参考PrefabStageUtility.HandleUIReparentingIfNeeded
        /// </summary>
        /// <returns></returns>
        private static Canvas InstanceCanvas(Transform parent = null)
        {
            const string kUILayerName = "UI";
            GameObject root = EditorUtility.CreateGameObjectWithHideFlags("Canvas", HideFlags.DontSave);
            root.layer = LayerMask.NameToLayer(kUILayerName);
            Canvas canvas = root.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            root.AddComponent<CanvasScaler>();
            root.AddComponent<GraphicRaycaster>();
            if (parent)
            {
                canvas.transform.SetParent(parent, false);
            }
            return canvas;
        }
    }

    /// <summary>
    /// 缓存管理类
    /// </summary>
    public class ToolCacheManager
    {
        private static string mFontDataPath = "Assets/Main/Tools/Font/FontData.asset";

        private static string FontDataFolderPath
        {
            get { return Application.dataPath + "/Main/Tools/Font"; }
        }

        /// <summary>
        /// 保存设置的字体
        /// </summary>
        /// <param name="font"></param>
        public static void SaveFont(Font font)
        {
            CheckFontDataFolderExist();
            EditorFrameworkUtils.DeleteFile(FontDataFolderPath, "FontData.asset");
            FontData data = ScriptableObject.CreateInstance<FontData>();
            data.defaultFont = font;
            AssetDatabase.CreateAsset(data, mFontDataPath);
            EditorUtility.SetDirty(data);
        }

        /// <summary>
        /// 从FontData.asset获取字体
        /// </summary>
        /// <returns></returns>
        public static Font GetFont()
        {
            FontData fontData = AssetDatabase.LoadAssetAtPath<FontData>(mFontDataPath);
            if (fontData != null)
                return fontData.defaultFont;
            else
                return null;
        }

        /// <summary>
        /// 确保存放FontData.asset文件夹存在
        /// </summary>
        private static void CheckFontDataFolderExist()
        {
            if (!Directory.Exists(FontDataFolderPath))
            {
                Directory.CreateDirectory(FontDataFolderPath);
                AssetDatabase.Refresh();
            }
        }
    }
    [InitializeOnLoad]
    /// <summary>
    /// 
    /// </summary>
    public class UnityUIEvent
    {
        static UnityUIEvent()
        {
            ObjectFactory.componentWasAdded += ComponentWasAdded;
        }

        private static void ComponentWasAdded(Component obj)
        {
            Text text= obj.gameObject.GetComponent<Text>();
            if (text!=null)
            {
                text.font = ToolCacheManager.GetFont();
            }
        }
        
    }
}