using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ButtonLongPress : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
    const bool debug = false;

    [SerializeField]
    [Tooltip("How long must pointer be down on this object to trigger a long press")]
    private float holdTime = 1f;
    private float startClick;

    private bool held = false;
    public UnityEvent onClick = new UnityEvent();
    public UnityEvent onLongPress = new UnityEvent();

    private Image icon;

    private void Awake()
    {
        icon = GetComponent<Image>();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        if (debug)
		{
            Debug.Log("OnPointerDown");
		}
        held = true;
        startClick = Time.time;
        Invoke("OnLongPress", holdTime);
    }
    public void OnPointerExit(PointerEventData eventData)
    {
        if (debug)
        {
            Debug.Log("OnPointerExit");
        }
        CancelInvoke("OnLongPress");
        held = false;
        icon.fillAmount = 1.0f;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        if (debug)
        {
            Debug.Log("OnPointerUp");
        }
        CancelInvoke("OnLongPress");
        
    }

    void OnLongPress()
    {
        if (debug)
        {
            Debug.Log("OnLongPress");
        }
        icon.fillAmount = 1.0f;
        held = false;
        onLongPress.Invoke();
    }

    void Update()
    {
        if (held)
        {
            float ratio = Time.time - startClick;
            icon.fillAmount = ratio;
        }
    }
}