using UnityEngine;
using System.Collections;
using XInputDotNetPure; // Required in C#

public class PlayerMovement : MonoBehaviour 
{
	//Input
	public int playerIndex;
	private GamePadState state;
	private GamePadState prevState;

    public Transform playerObject;
	public Transform shadowObject;
	public float moveSpeed;

	void Start () 
	{
	}

	void LateUpdate () 
	{
		if (GameManager.currentState == GameManager.GameStates.Game)
		{
			prevState = state;
			state = GamePad.GetState((PlayerIndex)playerIndex);

			float xMove = state.ThumbSticks.Left.X;
			float yMove = state.ThumbSticks.Left.Y;

			Vector3 newMovementPos = new Vector3(xMove * moveSpeed, yMove * moveSpeed, 0)* Time.deltaTime;

			if ((newMovementPos.x > 0.01f || newMovementPos.x < -0.01f) ||
			     (newMovementPos.y > 0.01f || newMovementPos.y < -0.01f))
			{
				playerObject.eulerAngles = new Vector3(0, 0, getAngle(newMovementPos, Vector3.zero));
			}

			playerObject.rigidbody.velocity += newMovementPos;
			playerObject.rigidbody.angularVelocity = Vector3.zero;

			shadowObject.transform.position = playerObject.position;
			shadowObject.transform.localPosition = new Vector3(0, -0.2f, 0);
		}
	}

	public float getAngle(Vector3 a, Vector3 b) 
	{
		float angle =  Mathf.Rad2Deg * (Mathf.Atan2(a.y - b.y, a.x - b.x));
		
		if(angle < 0)
		{
			angle += 360;
		}
		
		return angle;
	}
}
