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

public class LaserManager : MonoBehaviour
{
    public float timer;
    public Animator animator;

    public AudioClip fireSound;
    public AudioSource source;

    private float timerCounter;
    private List<GameObject> laserParts = new List<GameObject>();
    private IEnumerator coroutine;

    private void Start()
    {
        foreach (Transform child in transform) 
        {
            laserParts.Add(child.gameObject);
            timerCounter = timer;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if(timerCounter < 0){
            timerCounter = timer;
            coroutine = ShootLaserParts();
            StartCoroutine(coroutine);
        }
        timerCounter -= Time.deltaTime;
    }

    IEnumerator ShootLaserParts() 
    {
        animator.SetBool("ChargeShot", true);
        LaserSound();
        yield return new WaitForSeconds(0.9f);

        foreach (GameObject part in laserParts) 
        {
            part.SetActive(true);
            yield return new WaitForSeconds(0.01f);
        }

        animator.SetBool("ChargeShot", false);
        yield return new WaitForSeconds(1);

        foreach(GameObject part in laserParts)
        {
            part.SetActive(false);
        }
    }

    public void LaserSound() 
    {
        source.PlayOneShot(fireSound);
    }
}
