using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace Sound
{
    [RequireComponent(typeof(AudioSource))]
    public class SoundEffect : MonoBehaviour
    {
        private UnityAction<SoundEffect> _onDestroy;

        private AudioSource _source;

        public void Play(AudioClip clip, float volume)
        {
            if (!_source)
                _source = GetComponent<AudioSource>();

            _source.clip = clip;
            _source.volume = volume;
            _source.Play();

            StartCoroutine(DestroyWithDelay(clip.length));
        }

        public void SetDestroyCallback(UnityAction<SoundEffect> onDestroy) => _onDestroy = onDestroy;

        private IEnumerator DestroyWithDelay(float delay)
        {
            yield return new WaitForSecondsRealtime(delay);

            _onDestroy?.Invoke(this);
        }
    }
}