using Godot;
using System;

public partial class NavigationTestEnemy : CharacterBody2D
{
	[Export]
	private float _movementSpeed = 300.0f;
	public const float JumpVelocity = -400.0f;

	private NavigationAgent2D _navigationAgent;

	public override void _Ready()
	{
		_navigationAgent = GetNode<NavigationAgent2D>("NavigationAgent2D");
	}

	public override void _PhysicsProcess(double delta)
	{
		var mousePosition = GetGlobalMousePosition();
		_navigationAgent.TargetPosition = mousePosition;

		var currentAgentPosition = GlobalPosition;

		var nexPathPosition = _navigationAgent.GetNextPathPosition();
		
		var newVelocity = currentAgentPosition.DirectionTo(nexPathPosition) * (_movementSpeed);

		// Navigation is over, can do other things
		if (_navigationAgent.IsNavigationFinished())
		{
			
			return;
		}
		
		if (_navigationAgent.AvoidanceEnabled)
		{
			_navigationAgent.SetVelocity(newVelocity);
			
		}
		else
		{
			_on_navigation_agent_2d_velocity_computed(newVelocity);
		}

		MoveAndSlide();
	}
	
	public void _on_navigation_agent_2d_velocity_computed(Vector2 safeVelocity)
	{
		this.Velocity = safeVelocity; 
		
	}

	// public override void _PhysicsProcess(double delta)
	// {
	// 	Vector2 velocity = Velocity;
	//
	// 	// Add the gravity.
	// 	if (!IsOnFloor())
	// 	{
	// 		velocity += GetGravity() * (float)delta;
	// 	}
	//
	// 	// Handle Jump.
	// 	if (Input.IsActionJustPressed("ui_accept") && IsOnFloor())
	// 	{
	// 		velocity.Y = JumpVelocity;
	// 	}
	//
	// 	// Get the input direction and handle the movement/deceleration.
	// 	// As good practice, you should replace UI actions with custom gameplay actions.
	// 	Vector2 direction = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
	// 	if (direction != Vector2.Zero)
	// 	{
	// 		velocity.X = direction.X * Speed;
	// 	}
	// 	else
	// 	{
	// 		velocity.X = Mathf.MoveToward(Velocity.X, 0, Speed);
	// 	}
	//
	// 	Velocity = velocity;
	// 	MoveAndSlide();
	// }

	
}
