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

public class DraggableLevelElement : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private GameObject m_draggableGameObject;
    public GameObject instantiatedGameObject;
    public GameObject parent;
    private bool baseObject = true;

    public void OnBeginDrag(PointerEventData eventData)
    {
        Canvas canvas = GetComponentInParent<Canvas>();
        if (canvas == null)
            return;

        if (baseObject)
        {

            if (parent == null)
            {
                m_draggableGameObject = Instantiate(instantiatedGameObject);
                m_draggableGameObject.transform.SetParent(canvas.transform, false);
            }
            else
            {
                m_draggableGameObject = (GameObject) Instantiate(instantiatedGameObject, parent.transform.position, Quaternion.identity);
                m_draggableGameObject.transform.SetParent(parent.transform, false);
            }
            m_draggableGameObject.transform.SetAsLastSibling();

            DraggableLevelElement draggable = m_draggableGameObject.GetComponent<DraggableLevelElement>();
            if (draggable)
                draggable.baseObject = false;
        }
        else
        {
            m_draggableGameObject = this.gameObject;
        }
            

        SetDraggedPosition(eventData);
    }

    public void OnDrag(PointerEventData data)
    {
        if (m_draggableGameObject != null)
            SetDraggedPosition(data);
    }

    public void OnEndDrag(PointerEventData data)
    {
        if (m_draggableGameObject != null)
        {
                    m_draggableGameObject = null;
        }
    }

    private void SetDraggedPosition(PointerEventData data)
    {
        if (parent == null)
        {
            var rt = m_draggableGameObject.GetComponent<RectTransform>();
            var canvasRt = GetComponentInParent<Canvas>().GetComponent<RectTransform>();
            Vector3 canvasPos;

            if (RectTransformUtility.ScreenPointToWorldPointInRectangle(canvasRt, data.position, data.pressEventCamera, out canvasPos))
            {
                rt.position = canvasPos;
            }
        }
        else
        {
            var t = m_draggableGameObject.GetComponent<Transform>();
            t.position = Camera.main.ScreenToWorldPoint(data.position) - new Vector3(0.0f, 0.0f, Camera.main.transform.position.z);
        }
    }
}
