using UnityEngine;
using System.Collections;

public class BasicMoveController : MonoBehaviour {

	public float WalkSpeed;
	public bool RotateToMovement;
	public float StillDeadZone=0.05f;
	public bool FullStopOnArrive=false;

	[HideInInspector]
	public Vector2 TargetPoint;

	public bool BackingUp { get; set; }


	// Use this for initialization
	void Start () {
		BackingUp = false;
	}
	
	void FixedUpdate () {
		Debug.DrawLine(transform.position, (Vector3)TargetPoint);

		if(RotateToMovement)
			RotateToFacing();

		Vector2 diff = TargetPoint - (Vector2)transform.position;
		if(diff.magnitude > StillDeadZone)
		{
			Vector2 targetspeed = WalkSpeed * diff.normalized;
			Vector2 deltaspeed = targetspeed - rigidbody2D.velocity;
			Vector2 force = rigidbody2D.mass * deltaspeed / Time.fixedDeltaTime;
			rigidbody2D.AddForce(force);
		}
		else if(FullStopOnArrive)
		{
			FullStop();
		}
		
	}
	
	private void FullStop()
	{
		Vector2 force = rigidbody2D.mass * -rigidbody2D.velocity / Time.fixedDeltaTime; 
		rigidbody2D.AddForce(force);
	}
	
	private void RotateToFacing()
	{
		Vector2 diff = TargetPoint - (Vector2)transform.position;
		float dx = diff.x;
		float dy = diff.y;
		float aimangle = Mathf.RoundToInt(Mathf.Atan2(dx, dy) * -180/Mathf.PI);
		if(!BackingUp)
			transform.eulerAngles = new Vector3(0,0,aimangle);
	}
	
}
