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

namespace GatherAndDefend
{
    [RequireComponent(typeof(AudioSource))]
    public class AudioPlayerComponent : MonoBehaviour
    {
        [SerializeField] private AudioTemplate[] playableSounds;
        private Dictionary<string, AudioTemplate> _playableSounds;

        private AudioSource _audioSource;

        private void Awake()
        {
            _audioSource = GetComponent<AudioSource>();
            _playableSounds = new Dictionary<string, AudioTemplate>();

            if (playableSounds == null || playableSounds.Length == 0) return;

            foreach (var sound in playableSounds)
            {
                _playableSounds.Add(sound.name, sound);
            }
        }

        public void PlaySound(string soundName, float volumeMultiplier = 1f, float overrideVolume = -1f)
        {
            if (_playableSounds.TryGetValue(soundName, out AudioTemplate sound))
            {
                PlaySound(sound, volumeMultiplier, overrideVolume);
            }
        }

        public void PlaySound(AudioTemplate sound, float volumeMultiplier = 1f, float overrideVolume = -1f)
        {
            _audioSource.clip = sound.GetRandomClip();
            _audioSource.pitch = sound.GetRandomPitch();
            _audioSource.volume = ((overrideVolume != -1f) ? overrideVolume : sound.GetVolumeToUse()) * volumeMultiplier;
            _audioSource.Play();
        }
    }
}