using UnityEngine;

public class PlatformPop : MonoBehaviour
{
	// When the clock hand ticks, the rotation moves the attached platforms
	// If a platform is moving UPWARD, and the player is standing on it, this will cause an overlap
	// Sometimes this overlap, when resolved by the physics engine, pushes the player off the platform
	// either by dropping them straight downward through it (which can also trigger the one-way platform script)
	// or by shoving them off the side

	// This is super feelbad, so here's a complex way of nudging the player upward for up-moving ticks.

	public float PopAccelXFactor = .2f;
	public float PopAccelYFactor = 1f;

	public float YThreshold = 0.1f;
	public float XThreshold = 0.5f;

	private OneWayPlatform platform;
	private Rigidbody2D playerRB;

	public void PopPlayer(Vector3 moveDelta)
	{
		if (!platform || !platform.isEnabled)
			return;

		if (!MovingUp(moveDelta))
			return;

		if (!IsPlayerStandingOnMe())
			return;

		DoPopPlayer(moveDelta);
	}

	private void DoPopPlayer(Vector3 moveDelta)
	{

		Vector3 accel = new Vector3(moveDelta.x * PopAccelXFactor, moveDelta.y * PopAccelYFactor, 0);
		Vector3 force = playerRB.mass * accel / Time.fixedDeltaTime;
		playerRB.AddForce(force);

		//Debug.Log("Platform at " + transform.position + " moving " + moveDelta + " popping player at " + Player.instance.position + "by " + accel);
	}

	private static bool MovingUp(Vector3 moveDelta)
	{
		return moveDelta.y > 0;
	}

	private bool IsPlayerStandingOnMe()
	{
		Vector3 p = Player.instance.position;
		float yfromTarget = Mathf.Abs(p.y - (transform.position.y + 1f));
		float xoffSet = Mathf.Abs(p.x - transform.position.x);

		if (yfromTarget > YThreshold)
			return false;

		if (xoffSet > XThreshold)
			return false;

		return true;
	}

	private void Start()
	{
		platform = GetComponent<OneWayPlatform>();
		playerRB = Player.instance.GetComponent<Rigidbody2D>();
	}
}
