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

public class spawn2 : MonoBehaviour
{

    public GameObject[] objectToSpawn;
    public GameObject Money;

    public bool spawn = true;
    public float spawnTime = .2f;
    public float percentMoney = .1f;
    public float percentDoubleSpawn = .5f;
    bool doubleSpawned = false;

    public float minY = -1.05f;
    public float maxY = 1.05f;
    public float minDistance = .5f;

    float lastSpawnPosition = -100;
    float nextSpawnTime = 0;

    int numMeteorites = 0;


    int cachedSpawns = 5;
    Queue<GameObject> recentlySpawned = new Queue<GameObject>();
    float minSpawnDistance = 1f;

    private void Update()
    {
        if (nextSpawnTime > 0)
        {
            nextSpawnTime -= Time.deltaTime;
            return;
        }

        float tempMin = minY, tempMax = maxY;
        Vector3 newPos = new Vector3(3, tempMin, 0);
        while (recentlySpawned.Select(x => ((x.transform.position - newPos).magnitude > minSpawnDistance)).Contains(false) && tempMin < maxY)
        {
            tempMin += 0.1f;
            newPos.y = tempMin;
        }
        if (tempMin > maxY) return;
        newPos.y = tempMax;
        while (recentlySpawned.Select(x => ((x.transform.position - newPos).magnitude > minSpawnDistance)).Contains(false) && tempMin < tempMax)
        {
            tempMax -= 0.1f;
            newPos.y = tempMax;
        }
        if (tempMax < tempMin) return;

        var posY = Random.Range(tempMin, tempMax);
        Debug.Log(posY);
        newPos.y = posY;
        int rdm = Random.Range(0, objectToSpawn.Length);
        GameObject toSpawn = objectToSpawn[rdm];
        if (Random.Range(0, 1f) < percentMoney) toSpawn = Money;
        GameObject m = Instantiate(toSpawn, newPos, Quaternion.identity);
        dpl_droite meteorite = m.GetComponent<dpl_droite>();
        if (meteorite != null) meteorite.number = numMeteorites++;

        if (recentlySpawned.Count == cachedSpawns) recentlySpawned.Dequeue();
        recentlySpawned.Enqueue(m);

        if (!doubleSpawned && Random.Range(0, 1f) < percentDoubleSpawn)
        {
            nextSpawnTime = spawnTime * Random.Range(.5f, .1f);
            doubleSpawned = true;
        }
        else
        {
            nextSpawnTime = spawnTime * Random.Range(.5f, 1.1f);
            doubleSpawned = false;
        }
    }

}