using UnityEngine;
using System.Collections;

public class CameraManager : MonoBehaviour
{
		public float minMargin;
		public float nextMargin;
		
		private GameObject target;
		private Vector3 nextCenter;
		private CharacterController controller;
		private bool needUpdateUP, needUpdateDOWN;
		public float speed;
		// Use this for initialization
		void Start ()
		{
				
				controller = this.GetComponent<CharacterController> ();
				target = GameObject.FindGameObjectWithTag ("Player");
		}
	
		// Update is called once per frame
		void Update ()
		{
		
				Vector3 worldPosTOP = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width / 2, Screen.height, 0f));
				Vector3 worldPosBOTTOM = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width / 2, 0, 0f));
				float dis = worldPosTOP.y - worldPosBOTTOM.y;
				//blocco update up
				if ((worldPosTOP.y - target.transform.position.y) < minMargin) {
						nextCenter = new Vector3 (this.transform.position.x, target.transform.position.y, this.transform.position.z);
						needUpdateUP = true;
				}
				if (needUpdateUP) {
						Debug.Log ("needUpdate");
						controller.Move ((nextCenter - this.transform.position) * Time.deltaTime * speed);
				}
						
				if ((nextCenter - this.transform.position).magnitude < 0.1f)
						needUpdateUP = false;
						
				//blocco update down
				
				if ((target.transform.position.y) < worldPosBOTTOM.y + minMargin) {
						nextCenter = new Vector3 (this.transform.position.x, target.transform.position.y, this.transform.position.z);
						needUpdateDOWN = true;
				}
				if (needUpdateDOWN) {
						Debug.Log ("needUpdate");
						controller.Move ((nextCenter - this.transform.position) * Time.deltaTime * speed);
				}
	
				if ((nextCenter - this.transform.position).magnitude < 0.1f)
						needUpdateDOWN = false;
					
		}
}
