using FishNet.Object;
using UnityEngine;

namespace Players
{
    [RequireComponent(typeof(Camera))]
    public sealed class CameraFollow : NetworkBehaviour
    {
        [SerializeField] private Vector3 _offset = new(-10, 15, -10);
        [SerializeField] private Vector3 _rotation = new(45, 45, 0);
        [SerializeField] private Transform _target;
        [SerializeField, Range(0f, 360f)] private float _orbitAngle;
        [SerializeField] private float _mouseOrbitSensitivity = 180f;

        private float _mouseOrbitAngle;

        public override void OnStartClient()
        {
            base.OnStartClient();
            
            if(!IsOwner)
                return;
            
            Camera cam = GetComponent<Camera>();
            cam.enabled = true;
        }
        
        private void Update()
        {
            if(!IsOwner || _target == null)
                return;
            
            if (Input.GetMouseButton(1))
                _mouseOrbitAngle += Input.GetAxis("Mouse X") * _mouseOrbitSensitivity * Time.deltaTime;
            
            var orbitRotation = Quaternion.Euler(0f, _orbitAngle + _mouseOrbitAngle, 0f);
            
            transform.position = _target.position + orbitRotation * _offset;
            transform.rotation = orbitRotation * Quaternion.Euler(_rotation);
        }
    }
}
