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

public class BuildingParent : MonoBehaviour
{
    public List<Building> BuildingPool;
    public List<Material> Buildingmaterials;
    public Building buildingObj;
    public Obstacle obstacleObj;

    public int index = 0;
    int iterator = 0;
    int counter = 0;
    bool PooledIt = false;
    public Obstacle InstantiatedObstacle;
    private void Start()
    {
        index = 1;
        Func();
    }
    private void FixedUpdate()
    {

        if (BuildingPool[index % BuildingPool.Count].PlayerExitedfromBuilding == true)
        {
            BuildingPool[index % BuildingPool.Count].PlayerExitedfromBuilding = false;
            index++;
            ObjPooler();
        }
        if (iterator < 1)
        {
            if (BuildingPool[iterator % BuildingPool.Count].PlayerExitedfromBuilding == true)
            {
                BuildingPool[iterator % BuildingPool.Count].PlayerExitedfromBuilding = false;
                iterator++;
            }
        }
    }
    [ContextMenu("Func")]
    public void Func()
    {
        //if (InstantiatedObstacle != null)
        //    Destroy(InstantiatedObstacle);
        for (int i = 0; i < 10; i++)
        {
            Building temp = Instantiate(buildingObj, transform);
            temp.transform.localPosition = new Vector3(0, 0, -10 * i);
            BuildingPool.Add(temp);
            int percentAge = Random.Range(0, 100);
            int percentAgeObstacle = Random.Range(0, 100);
            if (percentAge < 40)
            {
                int rand = Random.Range(0, Buildingmaterials.Count);
                for (int j = 0; j < temp.renderers.Count; j++)
                {
                    temp.renderers[j].material = Buildingmaterials[rand];
                }
            }
            if (percentAgeObstacle < 80)
            {
                InstantiatedObstacle = Instantiate(obstacleObj, temp.transform);
            }

        }
    }

    public void ObjPooler()
    {
        int temp = counter % BuildingPool.Count;
        BuildingPool[temp].transform.localPosition = new Vector3(0, 0, -100 - (10 * counter));
        counter++;
        if (InstantiatedObstacle != null)
            Destroy(InstantiatedObstacle.gameObject);
        int percentAgeObstacle = Random.Range(0, 100);
        if (percentAgeObstacle < 80)
            InstantiatedObstacle = Instantiate(obstacleObj, BuildingPool[temp].transform);

        int percentAge = Random.Range(0, 100);
        if (percentAge < 40)
        {
            int rand = Random.Range(0, Buildingmaterials.Count);
            for (int j = 0; j < BuildingPool[j].renderers.Count; j++)
            {
                BuildingPool[j].renderers[j].material = Buildingmaterials[rand];
            }
        }

    }
}
