using FishNet.Object;
using UnityEngine;
using IStalk.Eye;

namespace IStalk.Shared
{
    public class NoiseEmitter : NetworkBehaviour
    {
        private static DreadEconomy _cachedDread;

        [Server]
        public void EmitNoise(Vector3 position, float radius, float intensity)
        {
            if (_cachedDread == null)
                _cachedDread = FindAnyObjectByType<DreadEconomy>();

            if (_cachedDread != null)
                _cachedDread.AddNoiseBonus(intensity);

            EmitNoiseVisualObservers(position, radius);
        }

        [ObserversRpc]
        private void EmitNoiseVisualObservers(Vector3 position, float radius)
        {
            var pulse = new GameObject("NoisePulse");
            pulse.transform.position = position;
            var sr = pulse.AddComponent<SpriteRenderer>();
            sr.color = new Color(1f, 1f, 1f, 0.3f);
            pulse.transform.localScale = Vector3.zero;
            Destroy(pulse, 0.5f);
        }

        public static void ClearCache()
        {
            _cachedDread = null;
        }
    }
}
