﻿using UnityEngine;
using System.Collections;

namespace Gamelogic.Grids.Examples
{
	public class Flipper : GLMonoBehaviour
	{
		private const float FlipTime = 2f;

		private Vector2 cooldownRange = new Vector2(0.5f, 1.5f);
		private float cooldown;
		private bool canFlip;

		public void Awake()
		{
			cooldown = Random.Range(cooldownRange.x, cooldownRange.y);
			canFlip = true;
		}

		public void Update()
		{
			if (canFlip)
			{
				canFlip = false;
				StartCoroutine(Flip());
			}
		}

		private IEnumerator Flip()
		{
			float t = 0;
			float rFrom = transform.localRotation.eulerAngles.x;
			float rTo = transform.localRotation.eulerAngles.x + 180f;

			while (t < FlipTime)
			{
				t += Time.deltaTime;
				float r = Mathf.Lerp(rFrom, rTo, t/FlipTime);
				yield return null;
				transform.SetLocalRotationX(r + rFrom);
			}

			transform.SetLocalRotationX(rTo);
			StartCoroutine(DelayFlip());
		}

		private IEnumerator DelayFlip()
		{
			yield return new WaitForSeconds(cooldown);
			canFlip = true;
		}

	}
}