using UnityEngine;
using System.Collections.Generic;


public class CloudController : MonoBehaviour {

    public List<GameObject> clouds;
    private List<GameObject> activeClouds;
    private int ticks = 0;
    public float probabilityOfSpawning;
    public float rangeUpwards;
    public float minScale;
    public float maxScale;
    public float yHeight;
    public float xPos;
    public AnimationCurve cloudDistribution;
    public float speed;
    public bool canOverlap = true;
    private GameObject nextObject;

	// Use this for initialization
	void Start () {
        activeClouds = new List<GameObject>();
	}
	
	// Update is called once per frame
	void Update () {
        ++ticks;
        var randomNum = Random.Range(0f, 100f);
        //Debug.Log(randomNum);
        var randomIndex = Random.Range(0, clouds.Count);

        if (nextObject != null)
        {

        }
        else if (randomNum > probabilityOfSpawning)
        {
            //Debug.Log("Index:" + randomIndex);
            var cloud = Instantiate(clouds[randomIndex]);

            float yOffset = yHeight + cloudDistribution.Evaluate(Random.value) * rangeUpwards;

            cloud.transform.position = new Vector3(xPos, yOffset, 0);
            cloud.transform.parent = gameObject.transform;

            bool isCreated = true;
            if (!canOverlap)
            {
                var bounds = cloud.GetComponent<PolygonCollider2D>().bounds;
                for (int i = 0; i < activeClouds.Count; ++i)
                {
                    var otherBounds = activeClouds[i].GetComponent<PolygonCollider2D>().bounds;
                    Debug.Log("My bounds: " + bounds.size + ", other: " + bounds.size);

                    if (otherBounds.Intersects(bounds))
                    {
                        Destroy(cloud);
                        isCreated = false;
                        break;
                    }
                }
            }

            if (isCreated)
            {
                float randomSize = Random.Range(minScale, maxScale);
                cloud.transform.localScale = new Vector3(randomSize, randomSize, randomSize);
                activeClouds.Add(cloud);
            }
        }
       

        for (int i = activeClouds.Count - 1; i >= 0; --i)
        {
            var c = activeClouds[i];
            c.transform.position += new Vector3(-speed * Time.deltaTime, 0, 0);

            if (c.transform.position.x < -20)
            {
                Destroy(c);
                activeClouds.RemoveAt(i);
            }
        }
	}
}
