using UnityEngine;

public class WaveController : MonoBehaviour {

	public GameObject RingPrefab;

	private float[] wave;
	private GameObject[] rings;

	public int NumRings;
	public int TotalPoints;
	public int WaveLength;
	public float MaxHeight;

	public void Start() {
		InitializeWave();
		InvokeRepeating("UpdateWave", 0, .01f);
	}

	public void Update() {
		if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
            CreateWave();
        }
	}

	private void InitializeWave() {
		this.wave = new float[TotalPoints];
		for (int i = 0; i < this.wave.Length; i++) {
			this.wave[i] = 0;
		}

		this.rings = new GameObject[NumRings];
		for (int i = 0; i < NumRings; i++) {
			this.rings[i] = Instantiate(RingPrefab, transform);
			this.rings[i].GetComponent<SpriteRenderer>().sortingOrder = i;
		}
	}

	private void CreateWave() {
		if (wave[WaveLength - 1] > 0) {  // Already in a wave.
			return;
		}
		float deltaX = Mathf.PI / WaveLength;
		float x = 0;
		for (int i = 0; i < WaveLength; i++) {
			wave[i] = Mathf.Sin(x) * MaxHeight;
			x += deltaX;
		}
	}

	private void UpdateWave() {
		// Shift right.
		for (int i = TotalPoints - 1; i > 0; i--) {
			wave[i] = wave[i - 1];
			if (i > TotalPoints - WaveLength / 2) {
				float maxHeightForI = Mathf.Sin((i - TotalPoints - WaveLength) * Mathf.PI / WaveLength) * MaxHeight;
				wave[i] = Mathf.Min(wave[i], maxHeightForI);
			}
		}
		wave[0] = 0;

		// Update GameObjects.
		for (int i = 0; i < NumRings; i++) {
			var x = .09f + .677f * i / (float) NumRings;
			var y = .06f + wave[i * TotalPoints / NumRings];
			var z = Mathf.Abs(Camera.main.transform.position.z);
			this.rings[i].transform.position = Camera.main.ViewportToWorldPoint(new Vector3(x, y, z));
		}
	}
}
