using UnityEngine;
using UnityEngine.UI;

public class ResourceBuilding : Building, ICardHolder
{
    private ResourceBuildingData data;
    [SerializeField] private NonDroppableCardHoldArea output;
    [SerializeField] private PeopleCardHoldArea workers;
    [SerializeField] private Slider slider;

    private float nextProductionTimer;

    private void Awake()
    {
        output.cardHolder = this;
        workers.cardHolder = this;
        if (BuildingData != null)
        {
            Initiate(BuildingData);
            operational = true;
        }
    }

    public override void Initiate(BuildingData buildingData)
    {
        base.Initiate(buildingData);
        data = buildingData as ResourceBuildingData;
        nextProductionTimer = data.ProductionTime;
    }
    
    public override void Demolish()
    {
        workers.DropCards();
        base.Demolish();
    }

    private void Update()
    {
        // Resource production
        if (operational && output.IsEmptySlot() && workers.WorkerCount > 0)
        {
            nextProductionTimer -= GameManager.Instance.GameSpeed * workers.ProductionEfficiency;
            slider.value = (data.ProductionTime - nextProductionTimer) / data.ProductionTime;
            slider.transform.parent.gameObject.SetActive(true);

            if (nextProductionTimer <= 0)
            {
                Card card = Instantiate(data.ProducedCard.Prefab);
                card.Initiate(data.ProducedCard, output, this);
                nextProductionTimer = data.ProductionTime;
            }
        }
        else slider.transform.parent.gameObject.SetActive(false);
    }

    public bool CanAddCard(CardData card)
    {
        return operational && (
            card == data.ProducedCard || (
            card.CardType == CardType.Person));
    }

    public void AddCard(CardData card) { }

    public void RemoveCard(CardData card) 
    {
        if (card.CardType == CardType.Person)
        {
            if (workers.WorkerCount == 0) nextProductionTimer = data.ProductionTime;
        }
    }

}
