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 (_suppressTimer > 0) return;

            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);
        }

        private float _suppressTimer;

        [Server]
        public void Suppress(float duration)
        {
            _suppressTimer = duration;
        }

        public bool IsSuppressed => _suppressTimer > 0f;

        private void Update()
        {
            if (!IsServerInitialized) return;
            if (_suppressTimer > 0)
                _suppressTimer -= Time.deltaTime;
        }

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