using UnityEngine;

public class MovementOnSphereMechanic : UserAgentBaseClass
{
    public bool canMove;

    [SerializeField] private float _radius = 10f;
    [SerializeField] private float _speedAzimuth = 1f;
    [SerializeField] private float _speedElevation = 1f;



    [SerializeField] float _azimuth = 0f;    // In radians
    [SerializeField] float _elevation = 0f;  // In radians

    [SerializeField]
    float xInput;
    [SerializeField]
    float yInput;

    public Transform _transform;

    private void OnEnable()
    {
        _elevation = Mathf.Deg2Rad * 90;
        _azimuth = Mathf.Deg2Rad * 0;
    }

    void Update()
    {
        if (canMove)
        {
            ReceiveInput();
            HandleInput(xInput, yInput);
            UpdatePosition();
        }
    }

    public void ReceiveInput()
    {
        //red button if pressed is -0.5 x and 0.5y, else all 0
        //green 0.5 + 0.5

        float redX = buttonPad.redButtonState ? -0.5f : 0;
        float whitedX = buttonPad.whiteButtonState ? -0.5f : 0;
        float greenX = buttonPad.greenButtonState ? 0.5f : 0;
        float yellowX = buttonPad.yellowButtonState ? 0.5f : 0;

        xInput = redX + whitedX + greenX + yellowX;

        float redY = buttonPad.redButtonState ? 0.5f : 0;
        float whitedY = buttonPad.whiteButtonState ? -0.5f : 0;
        float greenY = buttonPad.greenButtonState ? 0.5f : 0;
        float yellowY = buttonPad.yellowButtonState ? -0.5f : 0;
        yInput = redY + greenY + yellowY + whitedY;
    }

    private void HandleInput(float h, float v)
    {
        //float h = Input.GetAxis("Horizontal");
        //float v = Input.GetAxis("Vertical");

        _azimuth += h * Time.deltaTime * (_speedAzimuth);
        _elevation += v * Time.deltaTime * _speedElevation;

        _azimuth = ClampAngleAzimuth(_azimuth);
        _elevation = ClampAngleElevation(_elevation);
    }

    private void UpdatePosition()
    {
        float x = _radius * Mathf.Cos(_elevation) * Mathf.Cos(_azimuth);
        float y = _radius * Mathf.Sin(_elevation);
        float z = _radius * Mathf.Cos(_elevation) * Mathf.Sin(_azimuth);

        _transform.localPosition = new Vector3(x, y, z);
    }
    private static float ClampAngleAzimuth(float angle)
    {
        while (angle > Mathf.PI)
        {
            angle -= 2f * Mathf.PI;
        }
        while (angle < -Mathf.PI)
        {
            angle += 2f * Mathf.PI;
        }
        return angle;
    }
    private static float ClampAngleElevation(float angle)
    {
        while (angle > Mathf.PI)
        {
            angle = Mathf.PI;
        }
        while (angle < 0)
        {
            angle = 0;
        }
        return angle;
    }

}
