using UnityEngine;

public class PlayerLook : MonoBehaviour
{
    public Transform CameraTransform;
    public Transform Head;

    public float RotateSpeed = 5;
    public float MaxLookAngle = 90f;

    private float m_verticalRotation = 0f;

    private Rigidbody m_rigidbody;
    private PlayerInputController input;
    private PlayerHeadController headController;

    private void Awake()
    {
        m_rigidbody = GetComponent<Rigidbody>();
        input = GetComponent<PlayerInputController>();
        headController = GetComponent<PlayerHeadController>();
    }

    private void FixedUpdate()
    {
        Vector2 m_lookAmt = input.LookAmount;

        if (m_lookAmt.magnitude <= 0.01f)
            return;

        if (!headController.isHoldingHead || input.ShiftPressed && headController.isHoldingHead)
        {
            float headRotation = m_lookAmt.x * RotateSpeed * Time.deltaTime;
            Head.Rotate(0, headRotation, 0);

            if (CameraTransform != null)
            {
                m_verticalRotation -= m_lookAmt.y * RotateSpeed * Time.deltaTime;
                m_verticalRotation = Mathf.Clamp(m_verticalRotation, -MaxLookAngle, MaxLookAngle);
                CameraTransform.localRotation = Quaternion.Euler(m_verticalRotation, 0, 0);
            }
        }
        else
        {
            float horizontalRotation = m_lookAmt.x * RotateSpeed * Time.deltaTime;
            Quaternion deltaRotation = Quaternion.Euler(0, horizontalRotation, 0);
            m_rigidbody.MoveRotation(m_rigidbody.rotation * deltaRotation);

            if (CameraTransform != null)
            {
                m_verticalRotation -= m_lookAmt.y * RotateSpeed * Time.deltaTime;
                m_verticalRotation = Mathf.Clamp(m_verticalRotation, -MaxLookAngle, MaxLookAngle);
                CameraTransform.localRotation = Quaternion.Euler(m_verticalRotation, 0, 0);
            }
        }
    }
}