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

public class PlayAudio : MonoBehaviour {

	private AudioSource audioSource;
	private AudioSource overWaterAudioSource;
	private AudioSource seagullAudioSource;
	private AudioSource underWaterAudioSource;
	public AudioClip overWaterAmbience;
	public AudioClip underWaterAmbience;
	public AudioClip seagullAmbience;
	public List<AudioClip> intoWaterSounds;
	public List<AudioClip> outOfWaterSounds;
	public List<AudioClip> bubbleSounds;
	public float bubbleSpawnProbability;
	public float seagullAmbienceVolume;
	private bool inWater;

	// Use this for initialization
	void Start () {

		// One shot audio
		audioSource = GetComponent<AudioSource>();

		// Ambient sounds
		overWaterAudioSource = gameObject.AddComponent<AudioSource>();
		overWaterAudioSource.clip = overWaterAmbience;
		overWaterAudioSource.playOnAwake = true;
		overWaterAudioSource.loop = true;
		overWaterAudioSource.Play ();

		seagullAudioSource = gameObject.AddComponent<AudioSource>();
		seagullAudioSource.clip = seagullAmbience;
		seagullAudioSource.playOnAwake = true;
		seagullAudioSource.volume = seagullAmbienceVolume;
		seagullAudioSource.loop = true;
		seagullAudioSource.Play ();

		underWaterAudioSource = gameObject.AddComponent<AudioSource>();
		underWaterAudioSource.clip = underWaterAmbience;
		underWaterAudioSource.playOnAwake = true;
		underWaterAudioSource.loop = true;
		underWaterAudioSource.Play ();
	}
	
	// Update is called once per frame
	void Update () {

		// Spawn bubble sound 
		if (inWater && Random.value > (1 - bubbleSpawnProbability)) {
			int audioClipIndex = Random.Range (0, bubbleSounds.Count);
			audioSource.pitch = Random.Range (0.8f, 1.2f);
			audioSource.volume = Random.Range (0.7f, 1.0f);
			audioSource.panStereo = Random.Range (-1f, 1f);
			audioSource.PlayOneShot (bubbleSounds [audioClipIndex]);
		}
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if(other.gameObject.CompareTag("Water"))
		{
			int audioClipIndex = Random.Range (0, intoWaterSounds.Count);
			audioSource.PlayOneShot (intoWaterSounds [audioClipIndex]);

			overWaterAudioSource.volume = 0f;
			seagullAudioSource.volume = 0f;
			underWaterAudioSource.volume = 1f;

			inWater = true;
		}
		else if (other.gameObject.CompareTag("Sky"))
		{
			int audioClipIndex = Random.Range (0, outOfWaterSounds.Count);
			audioSource.PlayOneShot (outOfWaterSounds [audioClipIndex]);

			overWaterAudioSource.volume = 1f;
			seagullAudioSource.volume = seagullAmbienceVolume;
			underWaterAudioSource.volume = 0f;

			inWater = false;
		}
	}
}
