using NodeCanvas.Framework;
using ParadoxNotion.Design;
using ParadoxNotion.Services;
using UnityEngine;

namespace Reset.Movement {

	[Category("Reset/Movement")]
	[Description("Process Y-axis movement for the agent")]
	// TODO: Rename to UpdateGravitytDirection
	public class UpdateGravityDirection : ActionTask<CharacterController>{
		public BBParameter<Vector3> moveDirection;
		public BBParameter<float> jumpPower;
		public BBParameter<float> jumpPowerDecay;
		
		[Space(5)]
		public BBParameter<float> gravityAcceleration = 1f;
		public BBParameter<float> gravityMax = 8f;
		
		public BBParameter<float> gravityPower;
		
		//Use for initialization. This is called only once in the lifetime of the task.
		//Return null if init was successfull. Return an error string otherwise
		protected override string OnInit() {
			MonoManager.current.onLateUpdate += LateUpdate;
			return null;
		}

		//This is called once each time the task is enabled.
		//Call EndAction() to mark the action as finished, either in success or failure.
		//EndAction can be called from anywhere.
		protected override void OnExecute() {
		}

		//Called once per frame while the action is active.
		protected override void OnUpdate() {
			// Accelerate gravity
			gravityPower.value += gravityAcceleration.value * Time.deltaTime;
			gravityPower.value = Mathf.Min(gravityPower.value, gravityMax.value);
			
			// Apply a constant gravity if the player is grounded
			if (agent.isGrounded) {
				gravityPower.value = .1f;
			}
			
			// Create the gravity direction
			float gravityMoveDirection = jumpPower.value + Physics.gravity.y * gravityPower.value;
			
			// Commit gravity to move direction, ignoring XZ since those are done in UpdateMovementDirection
			moveDirection.value = new Vector3(moveDirection.value.x, gravityMoveDirection, moveDirection.value.z);

			Debug.Log("Gravity Done");

			EndAction(true);
			
		}
		public void LateUpdate(){
			// Decay jump power
			jumpPower.value = Mathf.Lerp(jumpPower.value, 0f, jumpPowerDecay.value * Time.deltaTime);
		}


		//Called when the task is disabled.
		protected override void OnStop() {
			
		}

		//Called when the task is paused.
		protected override void OnPause() {
			
		}
	}
}