using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Infrastructure.Unity
{
    public class RumbleManager : MonoBehaviour
    {
        private Coroutine _rumbleCoroutine;
        
        public void Pulse(float lowFrequency, float highFrequency, float duration)
        {
           if (Gamepad.current == null) return;
           
           if (_rumbleCoroutine != null) StopCoroutine(_rumbleCoroutine);
           
              _rumbleCoroutine = StartCoroutine(RumbleRoutine(lowFrequency, highFrequency, duration));
        }
        
        public void PulseLight() => Pulse(0.1f, 0.2f, 0.1f);
        public void PulseMedium() => Pulse(0.4f, 0.5f, 0.2f);
        public void PulseHeavy() => Pulse(0.8f, 1.0f, 0.3f);
        
        private IEnumerator RumbleRoutine(float low, float high, float duration)
        {
            Gamepad.current.SetMotorSpeeds(low, high);
            yield return new WaitForSeconds(duration);
            Gamepad.current.SetMotorSpeeds(0f, 0f);
        }

        private void OnDisable()
        {
            if (Gamepad.current != null)
                Gamepad.current.SetMotorSpeeds(0f, 0f);
        }
        
        public void SetPaused(bool isPaused) 
        {
            if (Gamepad.current != null)
            {
                if (isPaused)
                    Gamepad.current.PauseHaptics();
                else
                    Gamepad.current.ResumeHaptics();
            }
        }
    }
}