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

public class DraggableGameObject : MonoBehaviour
{
    private bool wasDragging = false;

    public void OnMouseDrag()
    {
        if (!wasDragging && rayCastEventSystemFromMouse().Count > 0)
        {
            return;
        }

        Vector3 screenCoordinates = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f);
        Vector3 worldCoordinates = Camera.main.ScreenToWorldPoint(screenCoordinates);
        Vector3 newPosition = Vector3.Lerp(gameObject.transform.position, worldCoordinates, 75.0f * Time.deltaTime);
        gameObject.transform.position = newPosition;

        wasDragging = true;
    }

    public void OnMouseUp()
    {
        if (wasDragging)
        {
            if (rayCastEventSystemFromMouse().Count > 0)
            {
                Destroy(this.gameObject);
            }
        }
    }

    private List<RaycastResult> rayCastEventSystemFromMouse()
    {
        PointerEventData ped = new PointerEventData(EventSystem.current);
        List<RaycastResult> raycastResults = new List<RaycastResult>();
        ped.position = Input.mousePosition;

        EventSystem.current.RaycastAll(ped, raycastResults);
        return raycastResults;
    }
}
