using UnityEngine;
using System.Linq;
using ScrambleKit.Extensions;

namespace ScrambleKit.FX
{
    public class SoundFX : MonoBehaviour
    {

        public static void PlaySound(string name, float vol=-1)
        {
            if (instance == null)
            {
                Debug.LogError("You must have an instance of ScrambleKit.FX.SoundFX to play sounds.  Cannot play sound: " + name);
                return;
            }

            if(instance.SoundLibrary == null)
            {
                Debug.LogError("Your instance of ScrambleKit.FX.SoundFX has no ScrambleKit.FX.SoundLibrary assigned.  Cannot play sound: " + name);
                return;
            }

            SoundEntry s = instance.SoundLibrary.Sounds.Where(e => e.Name == name).FirstOrDefault();
            if (s == null)
            {
                Debug.LogError("Your ScrambleKit.FX.SoundLibrary does not countain a sound named " + name);
                return;
            }

            if (s.PitchVariance == 0)
            {
                instance.asrc.PlayOneShot(s.Sounds.DrawFromAtRandom(), (vol == -1) ? s.Volume : vol);
            }
            else
            {
                float pitch = 1f + Random.Range(-s.PitchVariance, s.PitchVariance);
                instance.varysrc.pitch = pitch;
                instance.varysrc.PlayOneShot(s.Sounds.DrawFromAtRandom(), (vol == -1) ? s.Volume : vol);
            }
        }

        public SoundLibrary SoundLibrary;
        public static SoundFX instance;

        private AudioSource asrc;
        private AudioSource varysrc;

        void Start()
        {
            if (instance != null)
                Destroy(instance.gameObject);
            DontDestroyOnLoad(gameObject);

            instance = this;
            asrc = gameObject.AddComponent<AudioSource>();
            varysrc = gameObject.AddComponent<AudioSource>();
        }

    }
}