using UnityEngine;
using System.Collections;

public class FoldController : MonoBehaviour
{
	[SerializeField]public bool folded = true; // set from editor or external
	[SerializeField]float foldingTime = 0.8f; // set from editor
	[SerializeField]float startDelay = 0.1f; // set from editor
	[SerializeField]float endDelay = 0.1f; // set from editor
	[SerializeField]Vector3 startPosition = Vector3.zero;
	[SerializeField]Vector3 endPosition = Vector3.up;

	float timer = 0;

	void Start ()
	{
		if (folded)
		{
			timer = 0;
			UpdateElementPosition (0);
		}
		else
		{
			timer = foldingTime + startDelay + endDelay;
			UpdateElementPosition (1);
		}
	}

	void UpdateElementPosition(float anim = 0)
	{
		anim = Mathf.Max (0f, anim);
		anim = Mathf.Min (1f, anim);
		transform.localPosition = Vector3.Lerp (startPosition, endPosition, anim);
	}

	void Update ()
	{
		if (folded)
		{
			if (timer > 0)
			{
				timer -= Time.deltaTime;
				if (timer < 0)
				{
					timer = 0;
				}
				UpdateElementPosition ((timer - startDelay) / foldingTime);
			}
		}
		else
		{
			if (timer < foldingTime + startDelay + endDelay)
			{
				timer += Time.deltaTime;
				if (timer > foldingTime + startDelay + endDelay)
				{
					timer = foldingTime + startDelay + endDelay;
				}
				UpdateElementPosition ((timer - startDelay) / foldingTime);
			}
		}
	}

	#if UNITY_EDITOR
	bool foldedEdit = true;
	void OnDrawGizmos()
	{
		if (foldedEdit != folded)
		{
			foldedEdit = folded;
			if (!Application.isPlaying)
			{
				Start();
			}
		}
		Vector3 start = transform.position + transform.rotation * startPosition;
		Vector3 end = transform.position + transform.rotation * endPosition;
		Gizmos.color = Color.green;
		Gizmos.DrawWireCube (start, new Vector3 (0.05f, 0.05f, 0.05f));
		Gizmos.DrawWireCube (end, new Vector3 (0.05f, 0.05f, 0.05f));
		Gizmos.DrawLine (start, end);
	}
	#endif
}