using UnityEngine;
using ScrambleKit;

public class PuckMove : MonoBehaviour
{
	public static float sensitivity = 0.5f;
	public float accelPerMouseUnit = 5f;

	public float maxAccel = 50f;
	public float maxSpeed = 25f;

	private float stunUntil;
	private Rigidbody2D rb2;

	private Vector2 mousePush;

	public void Stun(float duration)
	{
		stunUntil = Time.time + duration;
	}

	public bool IsStunned()
	{
		return (Time.time < stunUntil);
	}

	void Update()
	{
		CheckSensitivityConfigInputs();
		CheckMouseInput();
	}

	void FixedUpdate()
	{
		if (IsStunned())
		{
			mousePush = Vector2.zero;
			return;
		}

		ApplyPush();
	}

	private void CheckMouseInput()
	{
		Vector2 frameInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
		mousePush += sensitivity * frameInput;
	}

	private void ApplyPush()
	{
		Vector2 accel = accelPerMouseUnit * mousePush;
		Vector2 requestedSpeed = rb2.velocity + accel;
		requestedSpeed = requestedSpeed.normalized * Mathf.Min(requestedSpeed.magnitude, maxSpeed);
		
		rb2.AccelTowardVelocityByAtMost(requestedSpeed, maxAccel);

		//Vector2 force = rb2.mass * accel / Time.fixedDeltaTime;
		//rb2.AddForce(force);

		mousePush = Vector2.zero;
	}

	private static void CheckSensitivityConfigInputs()
	{
		if (Input.GetKeyDown(KeyCode.LeftBracket))
		{
			sensitivity = Mathf.Max(0.05f, sensitivity - 0.1f);
		}
		else if (Input.GetKeyDown(KeyCode.RightBracket))
		{
			sensitivity = sensitivity + 0.1f;
		}
		else if (Input.GetKeyDown(KeyCode.Backslash))
		{
			sensitivity = 0.5f;
		}
	}

	void Start()
	{
		Cursor.lockState = CursorLockMode.Locked;
		Cursor.visible = false;
		rb2 = GetComponent<Rigidbody2D>();
	}

}
