using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ButtonHelper : MonoBehaviour, IPointerClickHandler, IPointerDownHandler
{
    public UnityEvent onClick;

    private float downTime;
    private Vector2 downPosition;
    private bool isDown;

    private float MAX_TIME = 0.3f;
    private float MAX_DISTANCE = 0.05f;

    private void OnClick()
    {
        var s = GetComponent<Selectable>();
        if (s == null || s.interactable)
            onClick.Invoke();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        downTime = Time.time;
        downPosition = eventData.position;
        isDown = true;
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        var delta = downPosition - eventData.position;
        if (isDown && Time.time < downTime + MAX_TIME && delta.magnitude / Screen.width < MAX_DISTANCE)
        {
            OnClick();
        }
        isDown = false;
    }
}
