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

public class ObjectExplosion : MonoBehaviour {
	
	public GameObject objectPrefab;
	
	public Vector3 randomForce;
	
	public int minObjects = 5;
	public int maxObjects = 10;
	
	protected List<GameObject> objects;
	
	void Start () {
		
		int r = Random.Range(minObjects, maxObjects);
		Vector3 cp = transform.position;
		objects = new List<GameObject>();
		for(int i=0;i<r;i++){
		
			
			Vector3 pos = new Vector3(cp.x+(Random.value-0.5f), cp.y+(Random.value*1.5f), cp.z+(Random.value-0.5f));
			
			if(Random.value > 0f)
				InstantiateManager.PlaceGameObject(pos, (pos-Camera.main.transform.position).normalized, this.transform);
			
			GameObject go = Instantiate(objectPrefab, pos, Random.rotation) as GameObject;
			go.rigidbody.AddForce(new Vector3(Random.value*randomForce.x, 50+Random.value*randomForce.y, Random.value*randomForce.z), ForceMode.Acceleration);
			objects.Add(go);
		}
		
		StartCoroutine(CleanupObjects());

	}
	
	IEnumerator CleanupObjects(){
		
		yield return new WaitForSeconds(5);
		while(objects.Count > 0){
		
			Destroy(objects[0]);
			objects.RemoveAt(0);
			yield return new WaitForSeconds(Random.Range(0.2f, 0.5f));
			
		}
		Destroy(this.gameObject);
	}
}
