using UnityEngine;
using UnityEditor;

namespace mgaia.Utils
{
    /// <summary>
    /// Editor de posicionamento de um grupo de elementos
    /// </summary>
    [CustomEditor(typeof(PositionSetterGroup))]
    public class PositionSetterGroupEditor : UnityEditor.Editor
    {
        private const int INDEX_FONT_SIZE = 20;
        private static readonly Color INDEX_TEXT_COLOR = Color.green;

        Tool LastTool = Tool.None;

        void OnEnable()
        {
            LastTool = Tools.current;
            Tools.current = Tool.None;
        }

        void OnDisable()
        {
            Tools.current = LastTool;
        }

        public void OnSceneGUI()
        {
            PositionSetterGroup positionSetterGroup = (PositionSetterGroup)target;

            if (positionSetterGroup.ObjectAndPositions != null)
            {
                for (int idx = 0; idx < positionSetterGroup.ObjectAndPositions.Length; idx++)
                {
                    ObjectAndPosition objectAndPosition = positionSetterGroup.ObjectAndPositions[idx];

                    Transform parentTransform = positionSetterGroup.ReferenceTransform;

                    Vector3 position = objectAndPosition.Position;
                    Vector3 handlePosition = parentTransform.TransformPoint(position);

                    objectAndPosition.Position = parentTransform.InverseTransformPoint(
                        Handles.PositionHandle(handlePosition, Quaternion.identity)
                        );

                    GUIStyle style = new GUIStyle();
                    style.fontSize = INDEX_FONT_SIZE;
                    style.normal.textColor = INDEX_TEXT_COLOR;
                    style.alignment = TextAnchor.MiddleCenter;

                    Handles.Label(handlePosition, idx.ToString(), style);
                }
            }
        }
    }
}