using UnityEngine;
using System.Collections;

public class RandomMover : MonoBehaviour
{ 
		public float speed;
		Vector3 vet;
		private float lastUpdate;
		public float secondsBetweenChange;
		private float rL, tL, lL, bL;
		public bool attivo{ get; set; }

		// Use this for initialization
		void Start ()
		{
				calcNewDirection ();
				lastUpdate = Time.time;
				rL = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width, 0, 0)).x;
				tL = Camera.main.ScreenToWorldPoint (new Vector3 (0, Screen.height, 0)).y;
				lL = Camera.main.ScreenToWorldPoint (new Vector3 (0, 0, 0)).x;
				bL = Camera.main.ScreenToWorldPoint (new Vector3 (0, 0, 0)).y;
		}
	
		// Update is called once per frame
		void Update ()
		{
				//Quaternion quat = Quaternion.Euler (new Vector3 (0.0f, 0.0f, Random.Range (0.0f, 360.0f)));
				//Quaternion.Euler = 			
				//this.transform.rotation = quat;
				//Debug.Log (quat);
				rL = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width, 0, 0)).x;
				tL = Camera.main.ScreenToWorldPoint (new Vector3 (0, Screen.height, 0)).y;
				lL = Camera.main.ScreenToWorldPoint (new Vector3 (0, 0, 0)).x;
				bL = Camera.main.ScreenToWorldPoint (new Vector3 (0, 0, 0)).y;
				if (Time.time - lastUpdate > secondsBetweenChange) {
						calcNewDirection ();
						lastUpdate = Time.time;
				}
				this.transform.position += clampedMovement ();
				//Vector3 vec = quat * Vector3.forward;
				//Debug.Log (vec);
				//this.transform.position = vec;


		}
		private void calcNewDirection ()
		{
				vet = new Vector3 (Random.Range (-1.0f, 1.0f), Random.Range (-1.0f, 1.0f), 0.0f);
		}
		private Vector3 clampedMovement ()
		{
				Vector3 toUse = new Vector3 (vet.x, vet.y, 0);
				if (this.transform.position.x > rL)
						toUse.x = toUse.x > 0 ? -toUse.x : toUse.x;
				else if (this.transform.position.x < lL)
						toUse.x = toUse.x > 0 ? toUse.x : -toUse.x;
				if (this.transform.position.y > tL)
						toUse.y = toUse.y > 0 ? -toUse.y : toUse.y;
				else if (this.transform.position.y < bL)
						toUse.y = toUse.y > 0 ? toUse.y : -toUse.y;
				vet = toUse;
				return toUse.normalized * speed * Time.deltaTime;
		}

}
