using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementBehaviour : MonoBehaviour  {
    [SerializeField]
    private float _movementSpeed = 10.0f;
    
    [SerializeField]
    private float _rotationSpeed = 10.0f;

    [Header("Player")]
    
    [SerializeField] 
    private float _playerHeight = 1.0f;
    
    [SerializeField]
    private float _playerRadius = 0.5f;
    
    private Vector3 _desiredMovementDirection = Vector3.zero;
    public Vector3 desiredMovementDirection
    {
        get => _desiredMovementDirection;
        set => _desiredMovementDirection = value;
    }
    
    public Vector3 desiredLookDirection
    {
        get => _desiredMovementDirection;
        set => _desiredMovementDirection = value;
    }
    private void Update()
    {
        HandleMovement();
        HandleRotation();
    }
    private void HandleMovement()
    {
        Vector3 movement = _desiredMovementDirection.normalized;
        float moveDistance = _movementSpeed * Time.deltaTime;
        bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * _playerHeight,
            _playerRadius, movement, moveDistance);
        
        if (!canMove) {
            // Cannot goto movedir
            
            Vector3 moveX = new Vector3(movement.x, 0, 0);
            canMove = movement.x != 0 && !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * _playerHeight,
                _playerRadius, moveX, moveDistance);

            if (canMove) {
                movement = moveX;
            } else {
                Vector3 moveZ = new Vector3(0, 0, movement.z);
                canMove = movement.z != 0 && !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * _playerHeight,
                    _playerRadius, moveZ, moveDistance);
                
                if (canMove) {
                    movement = moveZ;
                }
            }

        }
        if (canMove) {
            // movement *= _movementSpeed * Time.deltaTime;
            transform.position += movement * moveDistance;
        }            
    }

    private void HandleRotation() {
        transform.forward =
            Vector3.Slerp(transform.forward, _desiredMovementDirection, Time.deltaTime * _rotationSpeed);
    }

}
