using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

namespace TFramework
{
    /// <summary>
    /// 编辑器启动
    /// </summary>
    [InitializeOnLoad]
    public class EditorWindowTool
    {
        static EditorWindowTool()
        {
            EditorApplication.hierarchyWindowItemOnGUI += HierarchyItemChanged;

            if (EditorApplication.timeSinceStartup<30)
            {
                OnStart();
            }
            ImprotPackageManager.CheckImportPackage(()=> {
                EditorGlobalTool.AddDefineSymbols("INITFRAME");
            });
            OnAssetsEvent.CreateAssetEvent -= OnCreateScript;
            OnAssetsEvent.CreateAssetEvent += OnCreateScript;
        }

        private static void OnStart()
        {
            EditorGlobalTool.RemoveDefineSymbols("INITFRAME");
        }

        private static void HierarchyItemChanged(int instanceID, Rect selectionRect)
        {
           Object obj = EditorUtility.InstanceIDToObject(instanceID);
           if((obj as GameObject)?.GetComponent<Canvas>())
            {
                if((obj as GameObject).GetComponent<UIDomain>()==null && (obj as GameObject).name=="Canvas")
                {
                    (obj as GameObject).AddComponent<UIDomain>().m_domainName = UIManager.DEFAULTDOMAIN;
                }
            }
        }

        /// <summary>
        /// C#脚本被创建时事件
        /// </summary>
        /// <param name="path">文件路径</param>
        public static void OnCreateScript(string path)
        {
            path = path.Replace(".meta", "");
            if (path.EndsWith(".cs"))
            {
                string codes = File.ReadAllText(path);
                if (codes.Contains("TFramework")) return;
                int pos = codes.IndexOf("using");
                if (pos == -1)
                    pos = codes.IndexOf("namespace");
                if (pos == -1)
                    pos = codes.IndexOf("public");
                codes = codes.Insert(pos, "using TFramework;\n");
                File.WriteAllText(path, codes);
                AssetDatabase.Refresh();
            }
        }
    }
}
