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

public class ElementGenerator : MonoBehaviour {

    [SerializeField]
    GameObject ElementsTemplate;

    [SerializeField]
    Transform spawnerHolder;

    [SerializeField]
    Transform elementParent;

    public List<Transform> columnSpawners = new List<Transform>();

    [SerializeField]
    Transform imagesHolder;

    List<Sprite> elementSprites = new List<Sprite>();

    void Awake()
    {
        foreach(Transform trans in spawnerHolder)
        {
            columnSpawners.Add(trans);
        }

        foreach (Transform trans in imagesHolder)
        {
            elementSprites.Add(trans.GetComponent<SpriteRenderer>().sprite);
        }

       // StartGenerating();
    }

    public void StartGenerating()
    {
        for (int i = 0; i < 6; i++)
        {
            StartCoroutine(GenerateElements(columnSpawners[i].position, 6));
        }
    }

    public void EndGenerating()
    {
        StopAllCoroutines();
        foreach (Transform trans in elementParent)
        {
            Destroy(trans.gameObject);
        }


    }

    public IEnumerator GenerateElements(Vector3 spawnPoint, int amount)
    {
        for(int i = 0; i < amount; i++)
        {
            GameObject tmp = Instantiate(ElementsTemplate, spawnPoint, Quaternion.identity) as GameObject;
            tmp.GetComponent<Rigidbody2D>().isKinematic = false;
            tmp.transform.SetParent(elementParent);
            tmp.layer = 8;

            int rand = Random.Range(0, 6);

            tmp.GetComponent<SpriteRenderer>().sprite = elementSprites[rand];
            tmp.name = (rand + 1).ToString();

            yield return new WaitForSeconds(0.5f);
        }

        //print("PSAWN");
    }

    void CheckGrid()
    {

    }
}
