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

public class Generator : MonoBehaviour
{
    //Stage generator by Julia
    // Start is called before the first frame update
    [SerializeField] private List<GameObject> platforms;
    [SerializeField] private List<GameObject> enemies;
    [SerializeField] private float delay = 1f;
    [SerializeField] private float platformGenSpeed = 1f;
    //[SerializeField] private List<GameObject> spawnedPlatforms = new List<GameObject>();
    IEnumerator Start()
    {

        GenerateStart();
        StartCoroutine(GenerateEnemies());
        yield return StartCoroutine(GeneratePlatforms());
    }

    IEnumerator GenerateEnemies()
    {
        yield return StartCoroutine(GenerateEnemy());
        yield return StartCoroutine(GenerateEnemies());
    }

    IEnumerator GenerateEnemy()
    {
        yield return new WaitForSeconds(delay);
        GameObject newEnemy = Instantiate(enemies[Random.Range(0, enemies.Count)], GenCoords(), Quaternion.identity);
    }

    IEnumerator GeneratePlatforms()
    {
        
        yield return StartCoroutine(Generate());
        yield return StartCoroutine(GeneratePlatforms());
    }

    IEnumerator Generate()
    {
        
        yield return new WaitForSeconds(platformGenSpeed);
        GameObject newPlatform = Instantiate(platforms[Random.Range(0, platforms.Count)], GenCoords(), Quaternion.identity);
        //spawnedPlatforms.Add(newPlatform);
        
        
    }

    private void GenerateStart()
    {
        int i = 0;
        while (i < 5)
        {
            GameObject newPlatform = Instantiate(platforms[Random.Range(0, platforms.Count)], GenCoords(), Quaternion.identity);
            i++;
        }
    }

    private Vector2 GenCoords()
    {
        float spawnY = Random.Range
               (Camera.main.ScreenToWorldPoint(new Vector2(0, 10f)).y, Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height-30f)).y);
        float spawnX = Random.Range
            (Camera.main.ScreenToWorldPoint(new Vector2(10, 0)).x, Camera.main.ScreenToWorldPoint(new Vector2(Screen.width -30F, 0)).x);
        if (Physics2D.OverlapCircle(new Vector2(spawnX, spawnY), 3f) != null)
        {
            
            return GenCoords();

        }
        return new Vector2(spawnX, spawnY);
    }
        // Update is called once per frame
        void Update()
    {

        //if (spawnedPlatforms.Count < 5) Debug.Log("apua");    
    }
}
