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

public class SpikeLauncherController : MonoBehaviour
{
    [SerializeField] int numPooled = 10;
    [SerializeField] Vector2 direction;
    [SerializeField] float speed = 5f;
    [SerializeField] float launchInterval = 3.5f;
     
    List<GameObject> pooledSpikes = new List<GameObject>();
    GameObject spikePrefab;
    // Start is called before the first frame update
    void Start()
    {
        spikePrefab = Resources.Load<GameObject>("Prefabs/spike");
        for (int i = 0; i < numPooled; ++i)
        {
            GameObject tmp = Instantiate(spikePrefab, transform);
            tmp.SetActive(false);
            pooledSpikes.Add(tmp);
        }
        StartCoroutine(LaunchSpikes());

    }

    private IEnumerator LaunchSpikes()
    {
        while (true)
        {
            GameObject newSpike;
            foreach (GameObject s in pooledSpikes)
            {
                if (!s.activeInHierarchy)
                {
                    newSpike = s;
                    newSpike.SetActive(true);
                    yield return StartCoroutine(LoadSpike(newSpike));
                    newSpike.GetComponent<SpikeController>().SetVelocity(direction*speed);
                    break;
                }
            }
            yield return new WaitForSeconds(launchInterval); // Wait for the launch interval.


        }
    }

    private IEnumerator LoadSpike(GameObject spike)
    {
        Vector2 destination = new Vector2(transform.position.x, transform.position.y) + direction;
        while (Vector2.Distance(spike.transform.position, destination) > 0.01f)
        {
            spike.transform.position = Vector2.MoveTowards(spike.transform.position, destination, Time.deltaTime * speed*0.1f   );
            yield return null;
        }
        spike.transform.position = destination;

    }
}
