using System.Collections.Generic;
using UnityEngine;

public class ResourceManager : MonoBehaviour
{
    [SerializeField] private Dictionary<CardType, List<Card>> cards = new();

    private void Awake()
    {
        Events.OnAddCard += OnAddCard;
        Events.OnRemoveCard += OnRemoveCard;
        Events.OnRemoveCards += OnRemoveCards;
    }

    private void OnDestroy()
    {
        Events.OnAddCard -= OnAddCard;
        Events.OnRemoveCard -= OnRemoveCard;
        Events.OnRemoveCards -= OnRemoveCards;
    }

    private void OnAddCard(Card card)
    {
        if (card.cardData.CardType == CardType.Food)
            PeopleManager.Instance.FoodCount++;
        if (!cards.ContainsKey(card.cardData.CardType))
            cards[card.cardData.CardType] = new();
        cards[card.cardData.CardType].Add(card);
    }

    private void OnRemoveCard(Card card)
    {
        if (card.cardData.CardType == CardType.Food)
            PeopleManager.Instance.FoodCount--;
        cards[card.cardData.CardType].Remove(card);
        card.DestroyCard();
    }

    private void OnRemoveCards(CardType cardType, int amount)
    {
        if (!cards.ContainsKey(cardType)) return;
        if (cardType == CardType.Food)
            PeopleManager.Instance.FoodCount -= Mathf.Min(amount, cards[cardType].Count);
        for (int i = Mathf.Min(amount, cards[cardType].Count)-1; i >= 0; i--)
        {
            Card card = cards[cardType][i];
            cards[cardType].RemoveAt(i);
            card.DestroyCard();
        }
    }

}
