using UnityEngine;
using System.Collections;

public class Generator : MonoBehaviour {
	//Public
	[Header("Obiekty podpięte")]
	public GameObject	player			= null;
	public Transform	pillarGroup		= null;
	
	[Header("Dźwięki")]
	public AudioClip[]	sounds			= new AudioClip[12];
	
	[Header("Prefab")]
	public GameObject	pillarPrefab	= null;
	
	[Header("Dane")]
	public int			doSpawn			= 1;
	public bool			instantMode		= true;
	public float		spawnRadius		= 10f;
	public Color[]		spawnColors		= new Color[15];
	
	//Private
	private float		spawnTimer		= 0f;
	private float		doSpawnTimer	= 0f;
	private Vector3		tempPos			= Vector3.zero;
	private int			repeated		= 0;
	
	void Start() {
	
	}
	
	void FixedUpdate() {
		spawnTimer	+= Time.deltaTime;
		if (spawnTimer > 10f) {
			doSpawn		+= Random.Range(1, 3);
			spawnTimer	= 0f;
		}
	}
	
	void Update() {
		doSpawnTimer	+= Time.deltaTime;
		if (doSpawn > 0f && doSpawnTimer > 0.05f) {
			float		pillarHeight	= 3f + (Mathf.Abs(Random.value * 12f) * 0.5f);
			
			if (Random.value < 0.5f || repeated == 1) {
				tempPos	= new Vector3(
					Mathf.Floor(
						player.transform.position.x + Mathf.Ceil(Random.value) + ((Random.value - 0.5f) * spawnRadius)
					),
					-pillarHeight,
					Mathf.Floor(
						player.transform.position.z + Mathf.Ceil(Random.value) + ((Random.value - 0.5f) * spawnRadius)
					)
				);
				repeated	= 0;
			} else {
				repeated = 1;
			}
			
			GameObject	tempPillar				= (GameObject)Instantiate(pillarPrefab, tempPos, Quaternion.identity);
			tempPillar.transform.parent			= pillarGroup;
			
			tempPillar.transform.localScale		= new Vector3(
				1f + (Random.value * 0.4f),
				pillarHeight,
				1f + (Random.value * 0.1f)
			);
			
			tempPillar.renderer.material		= new Material(Shader.Find("Self-Illumin/Diffuse"));
			int	type	= (int)Mathf.Abs(Random.value * spawnColors.Length);
			tempPillar.renderer.material.color	= spawnColors[type];
			
			tempPillar.GetComponent<RaisePillar>().height		= pillarHeight;
			tempPillar.GetComponent<RaisePillar>().type			= type%sounds.Length;
			tempPillar.GetComponent<RaisePillar>().generator	= this;
			tempPillar.GetComponent<RaisePillar>().raise		= true;
			tempPillar.audio.clip							= sounds[type%sounds.Length];
			
			doSpawn	-= 1;
			doSpawnTimer	= 0f;
		}
	}
}
