using NodeCanvas.Framework;
using ParadoxNotion.Design;
using Reset.Movement;
using UnityEngine;
using UnityEngine.TextCore.Text;


namespace Reset.Player.Movement {
	[Category("Reset/Movement")]
	[Description("Finalizes the character rotation and commits it to the Transform")]
	// TODO: Rename to UpdateRotation
	public class UpdateRotation : ActionTask<CharacterController> {
		// Rotation
		public BBParameter<Vector3> moveDirection;
		
		public BBParameter<PlayerFacingDirection> playerFacingDirection;
		public BBParameter<float> rotationSpeed = 5f;
		public BBParameter<float> rotationSmoothing;

		private Vector3 currentMoveDir;
		private PlayerControls controls;
		
		private Quaternion targetRotation;
		private float currentRotSpeed;
		
		[ShowIf("playerFacingDirection", 0)]
		public Vector3 rotationTargetPosition;
		
		//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() {
			controls = agent.GetComponent<PlayerControls>();
			return null;
		}
		
		//Called once per frame while the action is active.
		protected override void OnUpdate() {
			// Calculate rotation speed
			currentRotSpeed = Mathf.Lerp(currentRotSpeed, rotationSpeed.value, rotationSmoothing.value * Time.deltaTime);
			
			// Set ingitial rotation power
			currentRotSpeed = rotationSpeed.value;
			
			// Get input value
			Vector3 inputMovement = new Vector3(controls.rawMoveInput.x, 0f, controls.rawMoveInput.y);
			
			switch (playerFacingDirection.value) {
				case PlayerFacingDirection.TowardsTarget:
					// Set rotation to just the direction of the target
					targetRotation = Quaternion.LookRotation((agent.transform.position.DirectionTo(rotationTargetPosition)).Flatten(null, 0));
					
					break;
				case PlayerFacingDirection.MatchForward:
					if (controls.rawMoveInput.magnitude < 0.01f) { break; }

					targetRotation = Quaternion.LookRotation(inputMovement) *
					                 Quaternion.Euler(Camera.main.transform.rotation.eulerAngles.Flatten(0f, null, 0f));

					break;
				case PlayerFacingDirection.MatchCamera:
					// Craft a new rotation that flattens the camera's rotation to the ground
					// Needed to keep the character from inheriting the camera's height-rotation
					targetRotation = Quaternion.Euler(Camera.main.transform.rotation.eulerAngles.Flatten(0, null, 0));
					break;
				case PlayerFacingDirection.Static:
					targetRotation = agent.transform.rotation;
					break;
			}
			
			// Set final rotation
			agent.transform.rotation = Quaternion.Lerp(agent.transform.rotation, targetRotation, 10f * Time.deltaTime).Flatten(0, null, 0);
			
			Debug.Log("Rotation Done");
			EndAction(true);
		}
		
		//Called when the task is disabled.
		protected override void OnStop() {
			
		}

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