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

public class Speaker : MonoBehaviour
{
    public AudioSource audioSource;
    public AudioClip preLoop, loop;

    public ParticleSystem bigWave, smallWave;

    public float bigWaveRadius = 7, smallWaveRadius = 4;
    public CircleCollider2D cCollider;

    public SpriteRenderer ring;

    IEnumerator Start()
    {
        while (loop.loadState == AudioDataLoadState.Loading)
            yield return null;
        audioSource.clip = preLoop;
        audioSource.loop = false;
        audioSource.Play();
        while (audioSource.isPlaying)
            yield return null;
        audioSource.Stop();
        audioSource.clip = loop;
        audioSource.loop = true;
        audioSource.Play();

        float step = 6;
        int currentStep = 0;
        int totalSteps = Mathf.CeilToInt(loop.length / step);
        print("Loop time: " + loop.length + ", TotalSteps: " + totalSteps);
        print("Last step: " + step * (totalSteps - 1));
        while (audioSource.isPlaying)
        {
            for (currentStep = 0; currentStep < totalSteps; currentStep++)
            {                
                while (currentStep * step > audioSource.time)
                {
                    yield return null;
                }
                print("Counter: " + currentStep + ", Threshold: " + currentStep * step + ", Time: " + audioSource.time);
                spawnWave(currentStep % 3 == 1);
            }
            while (audioSource.time > (totalSteps - 1) * step)
                yield return null;
            
            yield return null;
        }
    }

    void spawnWave(bool bigWave)
    {
        ParticleSystem ps = bigWave ? this.bigWave : this.smallWave;
        GameObject otherPs = bigWave ? this.smallWave.gameObject : this.bigWave.gameObject;

        float duration = ps.main.duration;

        ps.gameObject.SetActive(true);
        otherPs.SetActive(false);

        print("Spawned sound wave: " + (bigWave ? "Big" : "Small"));


        StartCoroutine(Utils.CrossFade(new Color(1, 1, 1, 0), Color.white, 0.3f, (dcol) =>
        {
            ring.color = dcol;
        }, () =>
        {
            StartCoroutine(Utils.CrossFade(Color.white, new Color(1, 1, 1, 0), 0.3f, (dcol) =>
            {
                ring.color = dcol;
            }));
        }));

        StartCoroutine(Utils.DoDelayed(duration * 2, () =>
        {
            ps.gameObject.SetActive(false);
        }));

        float radius = bigWave ? bigWaveRadius : smallWaveRadius;
        cCollider.radius = 0.5f;
        cCollider.gameObject.SetActive(true);
        StartCoroutine(Utils.DoOverTime(duration, (dt) =>
        {
            cCollider.radius = Mathf.Lerp(0.5f, radius, dt);
        }, () =>
        {
            cCollider.gameObject.SetActive(false);
        }));
    }

    void fade(SpriteRenderer spren, float fromAlpha, float toAlpha)
    {

    }
}
