
using System.Collections.Generic;
using UnityEngine;


public class TrafficPool : MonoBehaviour
{
    public static TrafficPool Instance { get; private set; }

    [System.Serializable]
    public class PoolEntry
    {
        public GameObject prefab;
        public int size;
    }

    [Header("Настройки пула")]
    public List<PoolEntry> poolEntries;

    private Dictionary<GameObject, Queue<TrafficCar>> _poolDictionary;

    void Awake()
    {
        if (Instance == null) Instance = this;
        else Destroy(gameObject);

        _poolDictionary = new Dictionary<GameObject, Queue<TrafficCar>>();

        foreach (var entry in poolEntries)
        {
            Queue<TrafficCar> objectPool = new Queue<TrafficCar>();
            for (int i = 0; i < entry.size; i++)
            {
                GameObject car = Instantiate(entry.prefab, transform);
                car.transform.rotation = Quaternion.identity;
                car.SetActive(false);
                
                TrafficCar carComponent = car.GetComponent<TrafficCar>();
                carComponent.originalPrefab = entry.prefab;
                
                objectPool.Enqueue(carComponent);
            }
            _poolDictionary.Add(entry.prefab, objectPool);
        }
    }

    public TrafficCar GetCar()
    {
        if (poolEntries.Count == 0) return null;
        PoolEntry randomEntry = poolEntries[Random.Range(0, poolEntries.Count)];
        
        Queue<TrafficCar> carQueue = _poolDictionary[randomEntry.prefab];

        if (carQueue.Count == 0)
        {
            Debug.LogWarning($"Пул для {randomEntry.prefab.name} пуст!");
            return null;
        }

        TrafficCar car = carQueue.Dequeue();
        return car;
    }

    public void ReturnCar(TrafficCar car)
    {
        if (car.originalPrefab != null && _poolDictionary.ContainsKey(car.originalPrefab))
        {
            car.gameObject.SetActive(false);
            _poolDictionary[car.originalPrefab].Enqueue(car);
        }
        else
        {
            Debug.LogWarning($"Не удалось вернуть машину {car.name} в пул. Уничтожение...");
            Destroy(car.gameObject);
        }
    }
}
