using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class UnityFakeEditorUtils
{
    public static GameObject[] SelectionObjects
    {
        get
        {
#if UNITY_EDITOR
            return Selection.gameObjects;
#else
            return null;
#endif
        }
    }

    public static void DrawTextSimple(Vector3 pos, string s, Color c)
    {
        DrawTextSimple(pos, s, c, FontStyle.Normal, 10);
    }

    public static void DrawTextSimple(Vector3 pos, string s, Color c, FontStyle fontStyle, int fontSize)
    {
#if UNITY_EDITOR
        var style = new GUIStyle
        {
            normal = { textColor = c },
            fontSize = fontSize,
            fontStyle = fontStyle
        };
        Handles.Label(pos, s, style);
#endif
    }

    /// <summary>
    /// Пример: GizmosUtils.DrawText(GUI.skin, "Custom text", transform.position, textColor, fontSize, yOffset);
    /// </summary>
    public static void DrawText(GUISkin guiSkin, string text, Vector3 position, Color? color = null, int fontSize = 0, float yOffset = 0)
    {
#if UNITY_EDITOR
        var prevSkin = GUI.skin;
        if (guiSkin == null)
            Debug.LogWarning("editor warning: guiSkin parameter is null");
        else
            GUI.skin = guiSkin;

        GUIContent textContent = new GUIContent(text);

        GUIStyle style = (guiSkin != null) ? new GUIStyle(guiSkin.GetStyle("Label")) : new GUIStyle();
        if (color != null)
            style.normal.textColor = (Color)color;
        if (fontSize > 0)
            style.fontSize = fontSize;

        Vector2 textSize = style.CalcSize(textContent);
        Vector3 screenPoint = Camera.current.WorldToScreenPoint(position);

        if (screenPoint.z > 0) // проверка, необходимая чтобы текст не был виден, если  камера направлена в противоположную сторону относительно объекта
        {
            var worldPosition = Camera.current.ScreenToWorldPoint(new Vector3(screenPoint.x - textSize.x * 0.5f, screenPoint.y + textSize.y * 0.5f + yOffset, screenPoint.z));
            UnityEditor.Handles.Label(worldPosition, textContent, style);
        }
        GUI.skin = prevSkin;
#endif
    }

    public static GameObject GetPrefab(GameObject clone)
    {
#if UNITY_EDITOR
        return PrefabUtility.FindValidUploadPrefabInstanceRoot(clone);
#endif
        return null;
    }

    public static GameObject ConnectToPrefab(GameObject target, GameObject prefab)
    {
#if UNITY_EDITOR
        return PrefabUtility.ConnectGameObjectToPrefab(target, prefab);
#endif
        return null;
    }
}