using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem.OnScreen;
using UnityEngine.InputSystem.Layouts;

namespace DeviantMobile.Input
{
    // A lightweight on-screen control we can pulse to simulate a button press.
    [AddComponentMenu("Input/On-Screen Pulse Control")]
    public class OnScreenPulseControl : OnScreenControl
    {
        // Shows an Input Control picker in the inspector; default layout Button.
        [SerializeField]
        [InputControl(layout = "Button")]
        private string m_ControlPath;

        protected override string controlPathInternal
        {
            get => m_ControlPath;
            set => m_ControlPath = value;
        }

        public void Pulse(float value = 1f, float duration = 0.05f)
        {
            // Send press then release after duration
            SendValueToControl(value);
            if (duration > 0f)
                // Use unscaled time so UI pulses are consistent across timeScale changes.
                StartCoroutine(ReleaseAfter(duration));
            else
                SendValueToControl(0f);
        }

        private IEnumerator ReleaseAfter(float duration)
        {
            // Use real-time wait to avoid being affected by Time.timeScale changes.
            yield return new WaitForSecondsRealtime(duration);
            SendValueToControl(0f);
        }
    }
}
