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

namespace AsmodeeDigital.PlayReal.Samples.UI
{
    [RequireComponent(typeof(RectTransform)), Serializable]
    public class DropSlot : MonoBehaviour, IDropHandler
    {
        [HideInInspector]
        public Draggable CurrentDraggable;

        public List<string> CompatibleDraggable;

        public UnityEvent OnDraggableAdded;
        public UnityEvent OnDraggableDeleted;

        public void OnDrop(PointerEventData eventData)
        {
            Draggable draggable = eventData.pointerDrag.GetComponent<Draggable>();

            if (draggable != null && CompatibleDraggable.Contains(draggable.tag))
            {
                if (draggable.DropSlot != null && draggable.DropSlot != this)
                {
                    GameObject.Destroy(draggable.gameObject);
                    draggable.DropSlot.OnDraggableDeleted.Invoke();
                    return;
                }

                if ((CurrentDraggable != null && CurrentDraggable != draggable))
                {
                    GameObject.Destroy(CurrentDraggable.gameObject);

                    OnDraggableDeleted.Invoke();
                }

                CurrentDraggable = draggable;
                OnDraggableAdded.Invoke();

                draggable.transform.SetParent(this.transform);
                draggable.RectTransform.anchoredPosition = Vector2.zero;
                draggable.DropSlot = this;
            }
        }
    }
}
