﻿#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using static ABI.CCK.Scripts.Editor.SharedComponentGUI;

namespace ABI.CCK.Components
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(CVRCanvasWrapper))]
    public class CCK_CVRCanvasWrapperEditor : Editor
    {
        private CVRCanvasWrapper _wrapper;

        private SerializedProperty m_InteractionDistanceProp;
        
        #region Unity Events

        private void OnEnable()
        {
            if (target == null) return;
            _wrapper = (CVRCanvasWrapper)target;
            
            m_InteractionDistanceProp = serializedObject.FindProperty(nameof(CVRCanvasWrapper.interactionDistance));
        }
        
        public override void OnInspectorGUI()
        {
            if (_wrapper == null)
                return;

            serializedObject.Update();

            EditorGUILayout.HelpBox("This component allows you to mark a Canvas for UI interaction within ChilloutVR. " +
                                    "It handles setting the Event Camera to the Local Player Camera automatically.", MessageType.Info);
            
            Draw_MissingComponentWarnings();
            Draw_Configuration();

            serializedObject.ApplyModifiedProperties();
        }
        
        #endregion Unity Events

        #region Drawing Methods
        
        private void Draw_MissingComponentWarnings()
        {
            if (!_wrapper.TryGetComponent(out Canvas _))
                EditorGUILayout.HelpBox("A Canvas is required for this component to function!", MessageType.Warning);
            
            if (!_wrapper.TryGetComponent(out GraphicRaycaster _))
                EditorGUILayout.HelpBox("A Graphics Raycaster is required if you want to interact with this Canvas!", MessageType.Warning);
            
            if (!_wrapper.TryGetComponent(out RectTransform _))
                EditorGUILayout.HelpBox("This component is expected to be on a GameObject with a RectTransform!", MessageType.Warning);
        }
        
        private void Draw_Configuration()
        {
            using (new LabelScope("Configuration"))
            {
                using (new EditorGUI.IndentLevelScope())
                    DrawConfiguration();
            }
        }

        private void DrawConfiguration()
        {
            GUILayout.BeginVertical();

            EditorGUILayout.PropertyField(m_InteractionDistanceProp);

            GUILayout.EndVertical();
        }

        #endregion Drawing Methods
    }
}
#endif