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

public class GrowingManager : MonoBehaviour
{

    public HeadController mainCell;

    [SerializeField]
    GrowingPanel growingPanelPrefab;
    Queue<GrowingPanel> usedGrowingPanelInstances = new Queue<GrowingPanel>();
    Queue<GrowingPanel> freeGrowingPanelInstances = new Queue<GrowingPanel>();

    void Update()
    {
        FreeGrowingPanelInstances();
        if(mainCell.HasNutrition())
            ShowGrowingPanels(mainCell);
    }

    void ShowGrowingPanels(HeadController headController)
    {
        foreach (var cell in headController.openCells)
        {
            foreach (var connection in cell.possibleConnections)
            {
                if (!connection.cell)
                {
                    ShowGrowingPanel(cell, connection);
                }
            }
        }
    }

    void ShowGrowingPanel(BaseCell cell, CellConnection connection)
    {
        var panel = GetGrowingPanelInstance();
        panel.transform.position = connection.transform.position;
        panel.transform.rotation = connection.transform.rotation;
        panel.Initialize(cell, connection);
    }

    void FreeGrowingPanelInstances()
    {
        while (usedGrowingPanelInstances.Count > 0)
        {
            var panelInstance = usedGrowingPanelInstances.Dequeue();
            panelInstance.gameObject.SetActive(false);
            freeGrowingPanelInstances.Enqueue(panelInstance);
        }
    }


    GrowingPanel GetGrowingPanelInstance()
    {
        GrowingPanel result;
        if (freeGrowingPanelInstances.Count > 0)
        {
            result = freeGrowingPanelInstances.Dequeue();
            result.gameObject.SetActive(true);
        }
        else
        {
            result = Instantiate(growingPanelPrefab);
            result.transform.SetParent(transform);
        }
        usedGrowingPanelInstances.Enqueue(result);
        return result;
    }
}
