using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.Tilemaps;

public class EntitySpawner : MonoBehaviour
{
    [FormerlySerializedAs("EntityToSpawn")] public GameObject entityToSpawn ;
    [FormerlySerializedAs("NumberOfInstances")] public int nbEntityInstances ;

    [FormerlySerializedAs("SpawnPositions")] public Vector2[] spawnPositions;
    [FormerlySerializedAs("TileGrid")] public GameObject grid;
    private GameObject[] _instances;
    private Transform _gridTransform;
    
    // EntitySpawnEvent is invoked by EntitySpawner upon spawning entity
    public delegate void EntitySpawnDelegate(Despawn d) ;
    public EntitySpawnDelegate EntitySpawnEvent ;
    
    void Start()
    
    {
        _instances = new GameObject[nbEntityInstances];
        for (int index = 0; index < nbEntityInstances; index++)
        {
            SpawnEntity(index) ;
        }
         
    }

    // GetEntityInstances returns the array of current instantiated entities
    GameObject[] GetEntityInstances()
    {
        return _instances;
    }
 
    // SpawnEntity spawns an entity at a random location in the provided locations array
    void SpawnEntity(int index) {
        Vector2 newPositionID = spawnPositions[Random.Range(0,spawnPositions.Length)] ; 
        _instances[index] = Instantiate(entityToSpawn, newPositionID, Quaternion.identity, grid.transform) ;
        Despawn despawn = _instances[index].GetComponent<Despawn>();
        despawn.EntityDespawnEvent += OnEntityDespawn;
        despawn.SetEntityIndex(index);
        EntitySpawnEvent?.Invoke(despawn);
    }

    void OnEntityDespawn(Despawn d){
        SpawnEntity(d.GetEntityIndex()) ;
    }
}
