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

public class RockSpawner : MonoBehaviour {

	public List<GameObject> rockPrefabs;
	public Vector2 spawnRadiusRange;
	public float spawnHeight;
	public int initialSpawnCount;
	public Vector2 initialSpawnWaitTimeRange;

	IEnumerator Start()
	{
		for(int i=0; i<initialSpawnCount; i++)
		{
			SpawnRandomRock();
			yield return new WaitForSeconds(Random.Range(initialSpawnWaitTimeRange.x, initialSpawnWaitTimeRange.y));
		}
	}

	public void SpawnRock(string name)
	{
		var rockPrefab = rockPrefabs.Find(x => x.name == name);
		if(rockPrefab != null)
		{
			SpawnRock(rockPrefab);
		}
	}

	public void SpawnRock(int index)
	{
		if(index >= 0 && index < rockPrefabs.Count)
		{
			SpawnRock(rockPrefabs[index]);
		}
	}

	public void SpawnRandomRock()
	{
		SpawnRock(rockPrefabs[Random.Range(0, rockPrefabs.Count)]);
	}

	private void SpawnRock(GameObject rockPrefab)
	{
		var angle = Random.value * 360f * Mathf.Deg2Rad;
		var radius = Random.Range(spawnRadiusRange.x, spawnRadiusRange.y);
		var randomPos = transform.position + radius * new Vector3(Mathf.Cos(angle), spawnHeight, Mathf.Sin(angle));
		var ray = new Ray(randomPos, Vector3.down);
		RaycastHit hit;
		if(Physics.Raycast(ray, out hit))
		{
			randomPos = hit.point + Vector3.up * 0.35f;
		}
		var randomRot = Quaternion.Euler(new Vector3(Random.value * 360f, Random.value * 360f, Random.value * 360f));
		var instance = Instantiate<GameObject>(rockPrefab);
		instance.transform.localPosition = randomPos;
		instance.transform.localRotation = randomRot;
	}
}
