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

public class UIInventorySlot : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler
{
    public GameObject item;

    /// <summary>
    /// A drag has begun!
    /// This is called on the Originating Slot
    /// </summary>
    /// <param name="eventData"></param>
    public void OnBeginDrag(PointerEventData eventData)
    {
        //move the item up in the hiearchy so it draws over other UI elements
        if (item != null)
        {
            item.transform.SetParent(transform.parent);
        }
    }

    /// <summary>
    /// Drag the selected item around
    /// This is called on the Originating Slot
    /// </summary>
    /// <param name="eventData"></param>
    public void OnDrag(PointerEventData eventData)
    {
        //update the item's screen position
        if (item != null)
        {
            item.transform.position = eventData.position;
        }
    }

    /// <summary>
    /// Receive a Drop event from the current Drag
    /// This is called on the Receiving Slot
    /// </summary>
    /// <param name="eventData"></param>
    public virtual void OnDrop(PointerEventData eventData)
    {
        UIInventorySlot from = eventData.pointerDrag.GetComponent<UIInventorySlot>();

        //make sure we don't already have an item
        if (item == null)
        {
            //accept drop
            item = from.item;
            item.transform.SetParent(transform);
            item.transform.localPosition = Vector3.zero;

            //open the other slot
            from.item = null;
        }
    }

    /// <summary>
    /// End the drag event
    /// This is called on the Originating Slot
    /// </summary>
    /// <param name="eventData"></param>
    public void OnEndDrag(PointerEventData eventData)
    {
        if (item != null && item.transform.parent == transform.parent)
        {
            item.transform.SetParent(transform);
            item.transform.localPosition = Vector3.zero;
        }
    }
}
