using System;
using UnityEngine;

public class SellCounter : BaseCounter {
    
    private bool _isSelling = false;
    
    private float _sellingPrice;
    public event EventHandler<OnCounterStartSellingArgs> OnCounterStartSelling;  //Event to notify that the counter is selling an item
    public class OnCounterStartSellingArgs : EventArgs {
        public SellCounter SellCounter;
    }

    public override void Interact(InteractionBehaviour interactionBehaviour) {
        if (!_isSelling) {
            //This counter is not selling an item yet
            if (interactionBehaviour.HasObject()) {
                //the player has something to sell
                Object obj = interactionBehaviour.GetObject();
                //Check if the object is sellable
                if (obj.TryGetComponent(out Object objectComponent)) {
                    Debug.Log("Player has something and it is sellable");
                    HUDManager.Instance.SellItem(this, objectComponent);
                }
                else {
                    Debug.Log("Player has something but it is not sellable");
                }
            }
        }
        else {
            //Player wants to pick up the item
            if (interactionBehaviour.HasObject()) {
                //Player is holding something, cant pickup
                return;
            }
            else {
                //Player has nothing
                //Take the object
                GetObject().setObjectParent(interactionBehaviour);
                _isSelling = false;
                
                CustomerManager.Instance.StoppedSelling(this);
            }
        }
    }

    //Gets called if an item is being sold on this counter
    //This should prevent the counter thinking it's selling something if the user cancels the UI sell
    public void ConfirmSell(Object obj, float price) {
        _isSelling = true;
        obj.setObjectParent(this);
        _currentObject = obj;
        _sellingPrice = price;
        
        OnCounterStartSelling?.Invoke(this, new OnCounterStartSellingArgs {SellCounter = this});

    }

    public void SellItem(CustomerController customerController) {
        this.GetObject().setObjectParent(customerController);
        _isSelling = false;
        GameController.Instance.Money += _sellingPrice;
    }

    public float GetSellingPrice() {
        return _sellingPrice;
    }
}