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

public class FloorRepairerDispenser : MonoBehaviour, IInteractable
{
    public Transform TransformComponent { get; private set; }

    private List<FloorRepairer> m_Active = new List<FloorRepairer>();

    [SerializeField] private int m_MaxInstances;
    [SerializeField] private FloorRepairer m_RepairerPrefab;

    public void Interact(PlayerController actor)
    {
        FloorRepairer repairer = null;

        foreach(FloorRepairer obj in m_Active)
        {
            if (!obj.gameObject.activeInHierarchy)
            {
                repairer = obj;
                m_Active.Remove(obj);
                m_Active.Add(obj);
                break;
            }
        }

        if (!repairer)
        {
            if (m_Active.Count < m_MaxInstances)
            {
                repairer = Instantiate(m_RepairerPrefab, TransformComponent.position, Quaternion.identity);
                m_Active.Add(repairer);
            }
            else
            {
                foreach(FloorRepairer obj in m_Active)
                {
                    if (obj.CanBeGrabbed)
                    {
                        repairer = obj;
                        m_Active.Remove(obj);
                        m_Active.Add(obj);
                        break;
                    }
                }
            }
        }

        repairer.gameObject.SetActive(true);
        repairer.transform.position = TransformComponent.position;
        actor.Grab(repairer);
    }

    private void Awake()
    {
        TransformComponent = transform;
    }
}
