using UnityEngine;
using Random = UnityEngine.Random;

public class TetrominoSpawnManager : MonoBehaviour
{
    private Vector3 spawnPoint;
    public GameObject tetrominoSquare;
    public GameObject tetrominoLine;
    public GameObject tetrominoL;
    public GameObject tetrominoR;
    public GameObject tetrominoS;
    public GameObject tetrominoT;
    public GameObject tetrominoZ;

    private int nextTetromino;
    private GameObject[] nextTetrominoSequence = new GameObject[14];

    public void Start()
    {
        spawnPoint = gameObject.transform.position;
        
        nextTetrominoSequence = new GameObject[]
        {
            tetrominoL, tetrominoL,
            tetrominoLine, tetrominoLine,
            tetrominoR, tetrominoR,
            tetrominoS, tetrominoS,
            tetrominoSquare, tetrominoSquare,
            tetrominoT, tetrominoT,
            tetrominoZ, tetrominoZ
        };
        
        Shuffle(nextTetrominoSequence);
    }

    public void spawnTetromino()
    {
        Instantiate(nextTetrominoSequence[nextTetromino], spawnPoint, Quaternion.identity);
        
        nextTetromino++;

        if (nextTetromino == 14)
        {
            nextTetromino = 0;
            Shuffle(nextTetrominoSequence);
        }

    }
    
    //an algorithm for shuffling arrays, taken from https://stackoverflow.com/questions/36702548/shuffle-array-in-unity
    void Shuffle(GameObject[] array)
    {
        int p = array.Length;
        for (int n = p - 1; n > 0; n--)
        {
            int r = Random.Range(0, n);
            (array[r], array[n]) = (array[n], array[r]);
        }
    }
}
