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

public class DJ : MonoBehaviour
{
    private AudioSource[] audios;

    private void Start()
    {
        audios = this.GetComponents<AudioSource>();

        StartCoroutine(MusicChange());
    }

    private IEnumerator MusicChange()
    {
        if (audios.Length > 0)
        {
            int rand = (int) Random.Range(1, audios.Length);

            StartCoroutine( FadeInOut(true, rand) );

            audios[rand].Play();

            yield return new WaitForSeconds(audios[rand].clip.length - 5f);

            StartCoroutine( FadeInOut(false, rand) );

            yield return new WaitForSeconds(5f);

            StartCoroutine(MusicChange());
        }
    }
    private IEnumerator FadeInOut(bool start, int pos, float Time = 5)
    {
        if( Time >= 0)
        {
            audios[pos].volume = 1f + ((start ? Time : 5 - Time) * 0.1f);
            yield return new WaitForSeconds(0.2f);
            Time -= 0.2f;
            StartCoroutine( FadeInOut( start, pos, Time ) );
        }
        else
        {
            yield return null;
        }
    }

    public void End()
    {
        foreach(AudioSource aus in audios)
        {
            StopAllCoroutines();
            aus.volume = 0.6f;
        }
        audios = null;
    }
}
