using UnityEditor;
using UnityEngine;

namespace AudioEvent
{
    [CustomEditor(typeof(AudioEvent), true)]
    public class AudioEventInspector : Editor
    {
        [SerializeField] private AudioSource _audioSource;

        private void OnEnable()
        {
            _audioSource =
                EditorUtility.CreateGameObjectWithHideFlags("Audio preview", HideFlags.HideAndDontSave,
                    typeof(AudioSource)).GetComponent<AudioSource>();
        }

        private void OnDisable()
        {
            DestroyImmediate(_audioSource.gameObject);
        }


        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
            if (GUILayout.Button("Preview"))
            {
                ((AudioEvent) target).Play(_audioSource);
            }

            EditorGUI.EndDisabledGroup();
        }
    }
}