﻿using UnityEngine;
using System.Collections;

namespace Gamelogic.Grids.Examples
{
	public class Dropper : GLMonoBehaviour
	{
		private const float DropTime = 3f;

		private Vector2 cooldownRange = new Vector2(0.5f, 1.5f);
		private float cooldown;
		private float dropDistance = -5f;
		private bool canMove;

		public void Awake()
		{
			cooldown = Random.Range(cooldownRange.x, cooldownRange.y);
			canMove = false;
			StartCoroutine(DelayMove());
		}

		public void Update()
		{
			if (canMove)
			{
				canMove = false;
				StartCoroutine(Drop());
			}
		}

		private IEnumerator Drop()
		{
			float t = 0;
			float yFrom = transform.localPosition.y;
			float yTo = transform.localPosition.y + dropDistance;

			while (t < DropTime)
			{
				t += Time.deltaTime;
				float y = Mathf.Lerp(yFrom, yTo, t/DropTime);
				yield return null;
				transform.SetLocalY(y);
			}

			transform.SetLocalY(yTo);
			ToggleDirection();
			StartCoroutine(DelayMove());
		}

		private void ToggleDirection()
		{
			dropDistance = -dropDistance;
		}

		private IEnumerator DelayMove()
		{
			yield return new WaitForSeconds(cooldown);
			canMove = true;
		}
	}
}