using FishNet.Object;
using FishNet.Object.Synchronizing;
using UnityEngine;

namespace IStalk.Props
{
    public class DynamicProp : PropBase
    {
        [SerializeField] private float _noiseRadius = 5f;
        [SerializeField] private AudioClip _interactSound;

        private readonly SyncVar<Vector3> _syncPosition = new(new SyncTypeSettings(0.05f));
        private readonly SyncVar<Quaternion> _syncRotation = new(new SyncTypeSettings(0.1f));

        public float NoiseRadius => _noiseRadius;

        public override void OnStartServer()
        {
            base.OnStartServer();
            _syncPosition.Value = transform.position;
            _syncRotation.Value = transform.rotation;
        }

        public override void OnStartClient()
        {
            base.OnStartClient();
            _syncPosition.OnChange += OnPositionChanged;
            _syncRotation.OnChange += OnRotationChanged;
        }

        [Server]
        public void ServerMove(Vector3 newPosition, Quaternion newRotation)
        {
            _syncPosition.Value = newPosition;
            _syncRotation.Value = newRotation;
            PlayInteractSoundObservers();
        }

        [ObserversRpc]
        private void PlayInteractSoundObservers()
        {
            if (_interactSound != null)
                AudioSource.PlayClipAtPoint(_interactSound, transform.position);
        }

        private void OnPositionChanged(Vector3 prev, Vector3 next, bool asServer)
        {
            transform.position = next;
        }

        private void OnRotationChanged(Quaternion prev, Quaternion next, bool asServer)
        {
            transform.rotation = next;
        }
    }
}
