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

public class SoundEmitter : MonoBehaviour
{

    public enum SoundType
    {
        GREEN, BLUE, PINK
    }
    public SoundType soundType;
    public float soundStartDelay;
    [Tooltip("Both duration and \"cooldown\" of a sound emitter")]
    public float soundWaveLength;
    //public Text emittingText;
    [HideInInspector]
    public float targetVolume = 0f;

    private bool isEmitting;
    private bool isPlaying;
    private bool fadeIn = false;
    private bool fadeOut = false;
    private float lastEmissionTime;
    private float timerStart = 0f;
    private bool startTimer = false;
    private AudioSource audioSource;

    // Use this for initialization
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        audioSource.Play();
        isEmitting = false;
        isPlaying = false;
        lastEmissionTime = -soundWaveLength;
    }

    // Update is called once per frame
    void Update()
    {
        if (!startTimer && timerStart >= soundStartDelay)
        {
            startTimer = true;
        }
        else
        {
            timerStart += Time.deltaTime;
        }

        //Duration to emit sound waves
        if (!isEmitting && startTimer && Time.time - lastEmissionTime >= soundWaveLength)
        {
            isEmitting = true;
            lastEmissionTime = Time.time;
            //emittingText.text = isEmitting + "";
        }

        //Duration to stop emitting sound waves
        if (isEmitting && Time.time - lastEmissionTime >= soundWaveLength)
        {
            isEmitting = false;
            lastEmissionTime = Time.time;
            //emittingText.text = isEmitting + "";
        }

        if (isEmitting && !isPlaying)
        {
            PlayEmitterSound();
        }

        if (fadeIn && audioSource.volume < targetVolume)
        {
            print("Increasing volume");
            audioSource.volume += Time.deltaTime;
        }

        if (fadeOut && audioSource.volume > 0f)
        {
            print("Decreasing volume");
            audioSource.volume -= Time.deltaTime;
        }

    }

    void PlayEmitterSound()
    {
        isPlaying = true;
        //audioSource.SetScheduledStartTime(Random.Range(0f, audioSource.clip.length - soundWaveLength));
        audioSource.time = Random.Range(0f, audioSource.clip.length - soundWaveLength);
        StartCoroutine(PlaySound());
    }

    IEnumerator PlaySound()
    {
        //audioSource.Play();
        fadeIn = true;
        //print("Fade in set to true");
        yield return new WaitForSeconds(soundWaveLength);
        fadeIn = false;
        //audioSource.Stop();
        fadeOut = true;
        //print("Fade out set to true");
        isPlaying = false;
        yield return new WaitForSeconds(1f);
        fadeOut = false;
    }

    public bool GetIsEmitting()
    {
        return isEmitting;
    }
}
