using System;
using System.Collections;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using ParadoxNotion.Services;
using Unity.Cinemachine;
using Unity.Mathematics;
using UnityEngine;
using Reset.Player.Movement;

namespace Reset.Player.Movement{
	public enum PlayerFacingDirection{
		Target = 0,
		Movement,
		MatchCamera,
		Static
	}
}


namespace NodeCanvas.Tasks.Actions {

	[Category("Reset/Movement")]
	[Description("Finalizes movement and sends the final move commands to the controller")]
	public class ProcessMovement : ActionTask<CharacterController>{
		public BBParameter<Vector3> groundMoveDirection;
		public BBParameter<Vector3> airMoveDirection;
		[Space(5)]
		public BBParameter<float> gravityAcceleration = 1f;
		public BBParameter<float> gravityMax = 8f;

		public BBParameter<float> jumpPower;
		public BBParameter<float> jumpPowerDecay;
		
		// Rotation
		public BBParameter<PlayerFacingDirection> playerFacingDirection;

		[ShowIf("playerFacingDirection", 0)]
		public Vector3 rotationTargetPosition;
		
		public BBParameter<float> rotationSpeed = 5f;
		public BBParameter<float> rotationSmoothing;

		private float currentRotSpeed;
		private float lastLookMagnitude;
		private Quaternion targetRotation;
		private Vector3 currentMoveDir;
		
		// References
		private PlayerControls controls;
		
		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() {
			// Append the late update method to actually happen on late update
			MonoManager.current.onLateUpdate += LateUpdate;
			
			// Set ingitial rotation power
			currentRotSpeed = rotationSpeed.value;
			
			// Reference to controls
			controls = agent.GetComponent<PlayerControls>();
			
			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(){
			currentMoveDir = groundMoveDirection.value;
		}

		//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);
			
			// Calculate rotation speed
			currentRotSpeed = Mathf.Lerp(currentRotSpeed, rotationSpeed.value, rotationSmoothing.value * Time.deltaTime);
			
			switch (playerFacingDirection.value) {
				case PlayerFacingDirection.Target:
					// Set rotation to just the direction of the target
					targetRotation = Quaternion.LookRotation((agent.transform.position.DirectionTo(rotationTargetPosition)).Flatten(null, 0, null));
					
					break;
				case PlayerFacingDirection.Movement:
					// Check magnitude to avoid the "Look rotation viewing vector is zero" debug

					// Set desired rotation to input direction, with respect to camera rotation
					if (agent.isGrounded){
						if (controls.rawMoveInput.magnitude == 0) { break; }

						targetRotation = Quaternion.LookRotation(currentMoveDir) *
						                 Quaternion.Euler(Camera.main.transform.rotation.eulerAngles.Flatten(0f, null, 0f));
					} else {
						if (airMoveDirection.value.magnitude == 0) { break; }

						targetRotation = Quaternion.LookRotation(airMoveDirection.value);
					}
					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;
			}
			
	        // Construct move direction
	        Vector3 finalMoveDir = Vector3.zero;
			Vector3 gravityMoveDirection;

			// Change how input is managed based on facing state
			currentMoveDir = Vector3.Slerp(currentMoveDir, groundMoveDirection.value, currentRotSpeed * Time.deltaTime);
			
			// Add input movement
			if (agent.isGrounded){
				finalMoveDir += currentMoveDir +  Vector3.down * .03f;
				gravityMoveDirection = new(0f, jumpPower.value + (Physics.gravity.y *.3f), 0f);
			} else {
				finalMoveDir += airMoveDirection.value;
				gravityMoveDirection = new(0f, jumpPower.value + Physics.gravity.y * gravityPower.value, 0f);
			}
			
			// Reset gravity power when grounded
			if (agent.isGrounded) {
				gravityPower.value = 0f;
			}
			
			// Do final movement
			if (agent.isGrounded) {
				agent.Move((Quaternion.Euler(Camera.main.transform.rotation.eulerAngles.Flatten(0f, null, 0f)) * finalMoveDir + gravityMoveDirection) * Time.deltaTime);
			} else {
				agent.Move((finalMoveDir + gravityMoveDirection) * Time.deltaTime);
			}
			
			// Set final rotation
			agent.transform.rotation = Quaternion.Lerp(agent.transform.rotation, targetRotation, 10f * Time.deltaTime).Flatten(0, null, 0);
			
			// ???? Moved this above but don't remember if this needs to be here still
			if (agent.isGrounded) {
				jumpPower.value = 0f;
			}
			EndAction(true);

		}
		
		// Gravity is processed in LateUpdate (added to MonoManager's onLateUpdate in OnInit())
		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() {
			EndAction(true);
		}

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