using UnityEngine;
using System.Collections;

public class PersonaControl : MonoBehaviour {

	#region Private Variables
	private float _targetOpacity = 0f;

	private float _duration = 10f;
	private float _startTime;
	private Vector3 _defaultPos;

	private SpriteRenderer _renderer;

	[SerializeField]
	private ConnectMechanic _mechanic;

	[SerializeField]
	private Collider2D _targetCollider;
	#endregion


	#region Getters and Setters
	public SpriteRenderer renderer {
		get {
			return _renderer;
		}
	}
	#endregion


	#region Events
	void Awake () {

		_renderer = GetComponent <SpriteRenderer> ();
		_defaultPos = transform.position;

	}

	void Update () {

		float t = (Time.time - _startTime) / _duration;
		float opacity = Mathf.Lerp (_renderer.color.a, _targetOpacity, t);

		_renderer.color = new Color (1f, 1f, 1f, opacity);

		if (t >= 0.5f) {
			_mechanic.CheckStage ();
		}
			
	}


	void OnBecameInvisible () {

		transform.position = _defaultPos;

	}


	void OnMouseUp () {

		Collider2D[] colliders = Physics2D.OverlapPointAll (transform.position);
		foreach (Collider2D c in colliders) {
			if (c == _targetCollider) {

				_targetCollider.GetComponent <ConnectControl> ().Morph ();
				_mechanic.CheckStage ();
				Destroy (gameObject);

			}
		}

	}
	#endregion


	#region Methods
	public void SetTargetOpacity (float t) {

		if (t < 0) t = 0;
		if (t > 1) t = 1;

		_targetOpacity = t;
		_startTime = Time.time;

	}
	#endregion
}
