using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(BoxCollider2D))]
public class Card : MonoBehaviour
{
    public CardData cardData;
    private CardHoldArea holdArea;
    private Building parent;

    public void Initiate(CardData data, CardHoldArea cardHoldArea, Building building)
    {
        cardData = data;
        holdArea = cardHoldArea;
        parent = building;
        holdArea.AddCard(this);
        Events.AddCard(this);
    }

    private void OnMouseDown()
    {
        if (!EventSystem.current.IsPointerOverGameObject() && GameManager.Instance.GameIsOn)
        {
            if (parent is not CardHolderBuilding ||
                MapManager.Instance.CheckIfBuildingTopIsOpen(
                    parent.transform.position, 
                    parent.BuildingData))
            {
                Events.CardForMovingSelected(parent, this);
            }
        }
    }

    public void PlaceCard(CardHoldArea cardHoldArea)
    {
        cardHoldArea.AddCard(this);
        holdArea?.RemoveCard(this);
        holdArea = cardHoldArea;
        parent = holdArea.GetComponentInParent<Building>();
    }

    public void DestroyCard()
    {
        holdArea.RemoveCard(this);
        Destroy(gameObject);
    }
}
