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

public class ObstacleController : MonoBehaviour {
	public WaveColor allowedWaveColor;
    public float anglesPerSecond = 0.0f;
	public float blinksPerSecond = 0.0f;
	public float colliderThreshold = 0.25f;
	public float phaseDuration = 0.5f;
	public float wobbleDistance = 0.0f;
	public float wobbleSpeed = 1.0f;
	public float wobbleRestDuration = 0.5f;

	Renderer _renderer;
	Collider2D _collider;

	float _alpha;
	float _alphaDelta;
	bool _pauseBlinky = false;

	public void Start() {
		this._renderer = this.GetComponent<Renderer> ();
		this._collider = this.GetComponent<Collider2D> ();

		this._alpha = this._renderer.material.color.a;
		this._alphaDelta = this.blinksPerSecond;

		if (this.wobbleDistance > 0.001f) {
			this.StartCoroutine (this.Wobble ());
		}
	}

    public void Update()
    {
        this.transform.Rotate(Vector3.forward, (Time.deltaTime * anglesPerSecond));

		if (this.blinksPerSecond > 0f && !this._pauseBlinky) {
			var color = this._renderer.material.color;
			var newAlpha = color.a + this._alphaDelta * Time.deltaTime;
			if (newAlpha < 0 || newAlpha > 1) {
				newAlpha = Mathf.Min (Mathf.Max (newAlpha, 0), 1);
				this._alphaDelta *= -1;
			}

			color.a = newAlpha;
			this._renderer.material.color = color;
			this._collider.enabled = newAlpha > this.colliderThreshold;

			if (newAlpha == 0) {
				this._pauseBlinky = true;

				this.ExecuteDelayedByTime (
					delegate() {
						this._pauseBlinky = false;
					},
					this.phaseDuration
				);
			}

		}
    }

	public IEnumerator Wobble() {
		var initialPos = this.transform.position;

		while (true) {
			var targetPos = initialPos + (Vector3)Random.insideUnitCircle * this.wobbleDistance;

			while ((targetPos - this.transform.position).sqrMagnitude > 0.01f) {
				this.transform.position = Vector3.MoveTowards (this.transform.position, targetPos, this.wobbleSpeed * Time.deltaTime);

				yield return null;
			}

			yield return new WaitForSeconds (this.wobbleRestDuration);
		}
	}
}

public enum WaveColor {
	Red,
	Blue,
	None,
	All
}