using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class OrbitalLine : MonoBehaviour
{

	public float startLineWidht = 0.065f;
	public float finalLineWidht = 0.055f;
	public int details = 85;
	public float radius = 1f;
	public float startAngle = 0;
	public Material lineMaterial = null;
	public float sectorAngle = 220f;//360;
	Transform selfTransform = null;
	LineRenderer line;

	public static OrbitalLine Create(GameObject gameObject, float radius, float startAngle, Material material)
	{
		OrbitalLine orbitalLine = gameObject.AddComponent<OrbitalLine> ();
		orbitalLine.lineMaterial = material;
		orbitalLine.radius = radius;
		orbitalLine.startAngle = startAngle;
		return orbitalLine;
	}

	void Awake ()
	{
		selfTransform = transform;
	}


	void Start ()
	{
		line = gameObject.GetComponent<LineRenderer> ();
		if (line == null) {
			line = gameObject.AddComponent<LineRenderer> ();
		}

		SetLineParams (details);
		selfTransform.eulerAngles = new Vector3 (0, startAngle, 0);
	}

	void SetLineParams(int details)
	{
		line.SetWidth (startLineWidht, finalLineWidht);
		line.SetColors (new Color (1f, 1f, 1f, 1f), new Color (1f, 1f, 1f, 0f));
		
		if (lineMaterial != null) {
			line.sharedMaterial = lineMaterial;
		}
		line.SetVertexCount (details);
		for (int i = 0; i < details; i++) {
			line.SetPosition (i, Quaternion.AngleAxis (i * ((-1f * sectorAngle) / (details - 1)), new Vector3 (0, 1, 0)) * new Vector3 (radius, 0, 0));
		}
		line.useWorldSpace = false;
	}

	#if UNITY_EDITOR
	float prevStartAngle = 0;
	float prevRadius = 1f;
	int prevDetails = 65;
	void OnDrawGizmos()
	{
		if (prevStartAngle != startAngle)
		{
			prevStartAngle = startAngle;
			selfTransform.eulerAngles = new Vector3(0, startAngle, 0);
		}
		if (prevRadius != radius)
		{
			prevStartAngle = radius;
			SetLineParams(details);
		}
		if (prevDetails != details)
		{
			prevDetails = details;
			SetLineParams(details);
		}
	}
	#endif
}