using UnityEngine.Audio;
using System;
using UnityEngine;

public class AudioManager : MonoBehaviour {
    
    public float audioFallOffSpeed;
	public bool resetValues = false;

	public Sound[] sounds;

	public static AudioManager instance;

    
    void Awake()
	{
		if (instance == null)
		{
			instance = this;
		}
		else
		{
			Destroy(gameObject);
			return;
		}

		DontDestroyOnLoad(gameObject);

		foreach (Sound s in sounds)
		{
			s.source = gameObject.AddComponent<AudioSource>();
			s.source.clip = s.clip;

			s.source.volume = s.volume;
			s.source.pitch = s.pitch; //* (1 + Random.Range(-s.randomPitch / 2.0f, s.randomPitch / 2.0f));
			s.source.loop = s.loop;
			s.source.outputAudioMixerGroup = s.mixerBus;
		}
	}

	void Start()
	{
		instance.Play("Ambience");
	}

	void Update()
	{
		if(resetValues)
		{
			ResetValues();
			resetValues = false;
		}

		for (int i=0; i<sounds.Length; i++)
		{
			sounds[i].Tick(Time.deltaTime);
		}

	}

	public void Play(string name)
	{
		Sound s = Array.Find(sounds, sound => sound.name == name);
		if (s == null)
		{
			Debug.LogWarning("Sound:" + name + " not found!");
			return;
		}

		s.isPlaying = true;
	}

	public void Stop(string name)
	{
		Sound s = Array.Find(sounds, sound => sound.name == name);
		if (s == null)
		{
			Debug.LogWarning("Sound:" + name + " not found!");
			return;
		}

		/*if(s.fadeOut)
		{
			s.isPlaying = false;
		}*/

		s.isPlaying = false;
	}

    [ContextMenu("Player Call received")]
    public void PlayCall ()
    {
        Play("light_turn_on");
    }

	void ResetValues()
	{
		foreach (Sound s in sounds)
		{
			s.source.clip = s.clip;

			s.source.volume = s.volume;
			s.source.pitch = s.pitch; //* (1 + Random.Range(-s.randomPitch / 2.0f, s.randomPitch / 2.0f));
			s.source.loop = s.loop;
		}
	}

    public void playRandomConvo ()
    {
        int randomInt = UnityEngine.Random.Range(1, 5);
        string randomString = "conversation_" + randomInt;
        Play(randomString);
    }
}
