using UnityEngine;
using System.Collections;

public class TouchMechanic : MonoBehaviour {

	#region Private Variables
	private int _count;
	private int _maxTouches = 10;
	private float _lastTouch;
	private float _offsetVanish = 5f;
	private float _startVanish;
	private float _endGameAtMark = 10f;
	private bool _scaleUp = false;
	private bool _scaleDown = false;

	private float _durationUp = 1.5f;
	private float _durationDown = 20f;
	private float _upperValue = 1.5f;
	private float _startTransition;

	[SerializeField]
	private TouchControl _touchControl;

	[SerializeField]
	private SpriteRenderer[] _sprites;

	private GameObject _room;
	#endregion


	#region Events
	void Start () {

		_lastTouch = Time.time;
		_startVanish = _lastTouch + _offsetVanish;
		_room = GameObject.FindGameObjectWithTag ("Room");

	}

	void OnMouseDown () {

		if (++_count < _maxTouches) {

			foreach (SpriteRenderer sr in _sprites)
				sr.color = new Color (1f, 1f, 1f, 1f);

			_lastTouch = Time.time;
			_startVanish = _lastTouch + _offsetVanish;

			if (!_touchControl.ActivateNext () && !_scaleUp) {
				_scaleUp = true;
				_startTransition = Time.time;
			}

		} else {

			_scaleDown = true;
			_startTransition = Time.time;

		}
		
	}

	void Update () {

		float passed = Time.time - _lastTouch;

		if (_scaleDown) {

			float t = (Time.time - _startTransition) / _durationDown;
			transform.localScale = Vector3.Lerp (transform.localScale, Vector3.zero, t);

			if (t >= 0.1f)
				KillRoom ();

		} else if (_scaleUp) {

			float t = (Time.time - _startTransition) / _durationUp;
			transform.localScale = Vector3.Lerp (transform.localScale, Vector3.one * _upperValue, t);

		}

		if (Time.time >= _startVanish) {

			float timeLeft = (_endGameAtMark - _startVanish);
			float t = (Time.time - _startVanish) / timeLeft;

			foreach (SpriteRenderer sr in _sprites)
				sr.color = new Color (1f, 1f, 1f, 1f - t);

		}

		if (_endGameAtMark <= passed) {
			
			KillRoom ();

		}

	}


	void KillRoom () {

		GameObject.FindObjectOfType <ActiveCamera> ().Reset ();
		Destroy (_room.gameObject);

	}
	#endregion
	
}
