using System.Collections.Generic;
using UnityEngine;

namespace Infrastructure.Unity
{
    public class TilePool
    {
        private readonly TileViewAdapter _prefab;
        private readonly Transform _parent;
        private readonly Stack<TileViewAdapter> _pool = new();
        
        public TilePool(TileViewAdapter prefab, Transform parent)
        {
            _prefab = prefab;
            _parent = parent;
        }
        
        public TileViewAdapter Get()
        {
            if (_pool.Count > 0)
            {
                var item = _pool.Pop();
                item.gameObject.SetActive(true);
                return item;
            }
            
            return Object.Instantiate(_prefab, _parent);
        }
        
        public void Return(TileViewAdapter item)
        {
            item.gameObject.SetActive(false);
            _pool.Push(item);
        }
    }
}
