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

[RequireComponent(typeof(Image))]
public class Dragable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler
{
    protected RectTransform m_DraggingPlane;

    private float lastClickTime = -1;

    public virtual void OnBeginDrag(PointerEventData eventData)
    {
        var canvas = FindInParents<Canvas>(gameObject);
        if (canvas == null)
            return;
     
        m_DraggingPlane = canvas.transform as RectTransform;
        transform.SetParent(m_DraggingPlane,false);

        SetDraggedPosition(eventData);
    }

    public virtual void OnDrag(PointerEventData data)
    {
            SetDraggedPosition(data);
    }

    protected virtual void SetDraggedPosition(PointerEventData data)
    {
        var rt = transform as RectTransform;
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
        {
            rt.position = globalMousePos;
            rt.rotation = m_DraggingPlane.rotation;
        }
    }

    public virtual void OnEndDrag(PointerEventData eventData)
    {

    }

    static public T FindInParents<T>(GameObject go) where T : Component
    {
        if (go == null) return null;
        var comp = go.GetComponent<T>();

        if (comp != null)
            return comp;

        Transform t = go.transform.parent;
        while (t != null && comp == null)
        {
            comp = t.gameObject.GetComponent<T>();
            t = t.parent;
        }
        return comp;
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (Time.time - lastClickTime <= 0.5f)
            OnDoubleClick();

        lastClickTime = Time.time;
    }

    protected virtual void OnDoubleClick() { }

}