using UnityEngine;
using System.Collections.Generic;

public class LevelSpawner : MonoBehaviour
{
    [System.Serializable]
    public class SpawnFurnishing
    {
        public GameObject prefab;
        public Vector3 size;
        public int count;
    }

    public SpawnFurnishing[] furnishings;
    public Bounds spawnBounds;

	void Start () 
    {
        var chosenBounds = new List<Bounds>();
        chosenBounds.Add(new Bounds(new Vector3(0f, 0f, 0f), new Vector3(1f, 1f, 1f)));

        foreach (var furnishing in furnishings)
        {
            for(int i = 0; i < furnishing.count; i++)
            {
				bool isValidPosition = false;
                Vector3 position = Vector3.zero;
                int attempts = 0;
                while (!isValidPosition)
                {
                    var chooseBounds = new Bounds(spawnBounds.center, spawnBounds.size - (furnishing.size));
                    var chooseLocation = new Vector3(Random.Range(chooseBounds.min.x, chooseBounds.max.x), 0f, Random.Range(chooseBounds.min.z, chooseBounds.max.z));
                    //Debug.Log("Trying: " + chooseLocation);
                    var newBounds = new Bounds(chooseLocation, furnishing.size);
                    isValidPosition = true;
                    foreach (var bound in chosenBounds)
                    {
                        if (bound.Intersects(newBounds))
                        {
                            //Debug.Log("failed.");
                            isValidPosition = false;
                            break;
                        }
                    }

                    if (isValidPosition)
                    {
                        //Debug.Log("success.");
                        chosenBounds.Add(newBounds);
                        position = newBounds.center;
                        break;
                    }

                    if(++attempts > 100)
                    {
                        break;
                    }
                }

                Instantiate(furnishing.prefab, position, Quaternion.identity);
            }
        }
	
	}

}
