using Cinemachine;
using RebootKit.Engine.Services.Simulation.Sensors;
using UnityEngine;

namespace RebootKit.FPPKit {
    public class FirstPersonCamera : MonoBehaviour {
        [SerializeField]
        private float _pickDistance = 5.0f;

        [SerializeField]
        private LayerMask _pickLayer;

        [field: SerializeField]
        public float Sensitivity { get; set; }

        [SerializeField]
        private float _pitchMin = -80f;

        [SerializeField]
        private float _pitchMax = 80f;

        [field: SerializeField]
        public CinemachineVirtualCamera Camera { get; private set; }

        public float Pitch { get; private set; }
        public float Yaw { get; private set; }

        private readonly RaycastSensor _raycastSensor = new();

        public ISensor Sensor {
            get {
                _raycastSensor.Ray = new Ray(Camera.transform.position, Camera.transform.forward);
                _raycastSensor.MaxDistance = _pickDistance;
                _raycastSensor.LayerMask = _pickLayer;
                return _raycastSensor;
            }
        }

        private void LateUpdate() {
            Camera.transform.localRotation = Quaternion.Euler(Pitch, 0f, 0f);
            transform.rotation = Quaternion.Euler(0f, Yaw, 0f);
        }

        public void Rotate(float x, float y) {
            float sens = Sensitivity;

            Pitch -= y * sens;
            Pitch = Mathf.Clamp(Pitch, _pitchMin, _pitchMax);

            Yaw += x * sens;
        }

        public void SetLookDirection(Vector3 forward) {
            Pitch = Mathf.Asin(-forward.y) * Mathf.Rad2Deg;
            Yaw = Mathf.Atan2(forward.x, forward.z) * Mathf.Rad2Deg;
        }
    }
}