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

public class RandomGen : MonoBehaviour
{

	public GameObject[] prefab;
	List<GameObject> prefabs;
	public Vector2 rangeX;
	public Vector2 rangeY;
	float contatore;
	GameObject band;
	bool needSpawn;
	public int offset;

	public float xOffset;

	public float force;

	void Start()
	{
		prefabs = new List<GameObject>();
		band = GameObject.Find("Band");
		needSpawn = true;
	}

	void Update() 
	{
		if((int)(band.transform.position.x + xOffset) % offset == 0 && needSpawn) {
			spawn(Random.Range(0, 10));
		}

		if((int)(band.transform.position.x + xOffset) % offset > 0 ) {
			needSpawn = true;
		}
	}

	void spawn(int mode) {
		if(mode < 4) {
			_throw();
		}
		else {
			_place();
		}
	}

	void _throw() {
		needSpawn = false;
		Vector3 position = new Vector3(band.transform.position.x + xOffset, Random.Range(rangeY[0],rangeY[1]), 0);
		GameObject boh = Instantiate(prefab[Random.Range(0,prefab.Length)], position, Quaternion.identity) as GameObject;
		boh.transform.SetParent(transform);
		prefabs.Add (boh);
		boh.GetComponent<Rigidbody2D>().AddForce(Vector2.up * Random.Range(force-.5f, force+.5f),
			ForceMode2D.Impulse);
	}

	void _place() {
		needSpawn = false;
		Vector3 position = new Vector3(band.transform.position.x + xOffset + Random.Range(15f, 20f), Random.Range(rangeY[0],rangeY[1]), 0);
		GameObject boh = Instantiate(prefab[Random.Range(0,prefab.Length)], position, Quaternion.identity) as GameObject;
		boh.transform.SetParent(transform);
		boh.GetComponent<Rigidbody2D>().gravityScale = 0;
		prefabs.Add (boh);
	}


}
