using UnityEngine;
using UnityEngine.EventSystems;

public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public float highlightScale;

    private Vector2 startPosition = Vector2.zero;

    private Vector3 originalScale;
    private Quaternion originalRotation;

    private void Awake()
    {
        this.startPosition = this.transform.position;
        this.originalScale = this.transform.localScale;
        this.originalRotation = this.transform.localRotation;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        LeanTween.cancel(this.gameObject);
        LeanTween.rotateLocal(this.gameObject, Vector3.zero, 0.2f);
        LeanTween.scale(this.gameObject, this.highlightScale * this.originalScale, 0.2f);

        var canvas = FindInParents<Canvas>(gameObject);
        if (canvas == null)
            return;
        
        SetDraggedPosition(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        // Cancelar drag voltando para a posicao inicial
        //eventData.position = this.startPosition;
        //SetDraggedPosition(eventData);

        LeanTween.move(this.gameObject, this.startPosition, 0.2f);
        LeanTween.rotateLocal(this.gameObject, this.originalRotation.eulerAngles, 0.2f);
        LeanTween.scale(this.gameObject, this.originalScale, 0.2f);
    }

    private void SetDraggedPosition(PointerEventData data)
    {
        var plane = this.transform as RectTransform;
        var rt = this.transform as RectTransform;
        Vector3 globalMousePos;

        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(plane, data.position, data.pressEventCamera, out globalMousePos))
        {
            rt.position = globalMousePos;
        }
    }
    
    static private 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;
    }
}