using UnityEngine;
using System.Collections;

[RequireComponent (typeof (MeshFilter))]
[RequireComponent (typeof (MeshRenderer))]
public class StarField : MonoBehaviour {
	
	[SerializeField] private Material material;
	[SerializeField] private float radius = 10;
	[SerializeField] private int starsCount = 500;
	[SerializeField] private float size = 0.5f;

	protected MeshFilter meshFilter;						
	protected MeshRenderer meshRenderer;
	
	Mesh CreateMesh(float radius, int details = 18){
		Quaternion rotation;
		Vector3[] vertices = new Vector3[starsCount * 4];
		Vector2[] textures = new Vector2[starsCount * 4];
		int[] triangles    = new int[starsCount * 6]; 
  		for(int i = 0; i < starsCount; i ++){
    		rotation = 
				Quaternion.AngleAxis(Random.Range(0, 360), new Vector3(0, 0, 1)) * 
				Quaternion.AngleAxis(Random.Range(0, 360), new Vector3(0, 1, 0)) * 
				Quaternion.AngleAxis(Random.Range(0, 360), new Vector3(1, 0, 0));
    		vertices[i * 4 + 0] = rotation * new Vector3( size, 0, radius);
    		vertices[i * 4 + 1] = rotation * new Vector3( 0, size, radius);
    		vertices[i * 4 + 2] = rotation * new Vector3(-size, 0, radius);
    		vertices[i * 4 + 3] = rotation * new Vector3( 0,-size, radius);
    		textures[i * 4 + 0] = new Vector2( 0, 0);
    		textures[i * 4 + 1] = new Vector2( 1, 0);
    		textures[i * 4 + 2] = new Vector2( 1, 1);
    		textures[i * 4 + 3] = new Vector2( 0, 1);			
		}
  		for(int i = 0; i < starsCount; i ++){
			triangles[i * 6 + 0] = i * 4 + 0;
			triangles[i * 6 + 1] = i * 4 + 2;
			triangles[i * 6 + 2] = i * 4 + 1;
			triangles[i * 6 + 3] = i * 4 + 0;
			triangles[i * 6 + 4] = i * 4 + 3;
			triangles[i * 6 + 5] = i * 4 + 2;
		}
		
		return new Mesh { vertices = vertices, uv = textures, triangles = triangles };
	}
		
	void Awake () {
		meshFilter   = Utils.GetOrCreateComponent<MeshFilter>(gameObject);
		meshRenderer = Utils.GetOrCreateComponent<MeshRenderer>(gameObject);
	}
		
	void Start () {
		meshFilter.mesh = CreateMesh(radius);
	}
	
	void Update () {
	
	}

	#if UNITY_EDITOR		
	float currentRadius;
	float currentSize;
	Material currentMaterial;
	
    void OnDrawGizmos() {
		bool needChange = false;		
		if (currentRadius != radius) {
			currentRadius = radius;
			needChange = true;
		}		
		if (currentSize != size) {
			currentSize = size;
			needChange = true;
		}
		if (currentMaterial != material){
			currentMaterial = material;
			if (meshRenderer == null) {
				meshRenderer = gameObject.GetComponent<MeshRenderer>();
			}
			meshRenderer.material = material;
		}
		if (needChange){
			if (meshFilter == null) {
				meshFilter = gameObject.GetComponent<MeshFilter>();
			}
			meshFilter.mesh = CreateMesh(radius);
			Resources.UnloadUnusedAssets();
		}
    }	
	#endif
}
