using UnityEngine;
using UnityEngine.UI;

public class FactoryBuilding : Building, ICardHolder
{
    private FactoryBuildingData data;
    [SerializeField] private ResourceCardHoldArea input;
    [SerializeField] private NonDroppableCardHoldArea output;
    
    [SerializeField] private PeopleCardHoldArea workers;
    [SerializeField] private Slider slider;

    private float nextProductionTimer;

    private void Awake()
    {
        input.cardHolder = this;
        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 FactoryBuildingData;
        nextProductionTimer = data.ProductionTime;
    }

    public override void Demolish()
    {
        workers.DropCards();
        base.Demolish();
    }

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

            if (nextProductionTimer <= 0)
            {
                for (int i = 0; i < data.InputAmount; i++)
                {
                    Events.RemoveCard(input.GetCard());
                }
                

                for (int i = 0; i < data.OutputAmount; i++)
                {
                    Card card = Instantiate(data.OutputResource.Prefab);
                    card.Initiate(data.OutputResource, output, this);
                }

                nextProductionTimer = data.ProductionTime;
            }
        }
        else slider.transform.parent.gameObject.SetActive(false);
    }

    public bool CanAddCard(CardData card)
    {
        return operational && (
            card == data.InputResource || (
            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;
        }
    }
}
