using System;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class ComputerBehaviour : MonoBehaviour, IInteractable {
    [SerializeField] private List<ObjectSO> _objectsToSell = new List<ObjectSO>();
    
    [SerializeField] private EmptyCounter _destinationCounter;
    
    [Range(0, 100)]
    [SerializeField] private int _brokenChance = 10;
    
    private ObjectSO _objectToSell;
    private bool _isBroken = false;
    
    public event EventHandler OnBuyItem;

    private void Start() {
        _objectToSell = GetRandomObject();
        _isBroken = GetRandomBroken();
    }
    
    private ObjectSO GetRandomObject() {
        return _objectsToSell[Random.Range(0, _objectsToSell.Count)];
    }
    
    private bool GetRandomBroken() {
        return Random.Range(0, 100) < _brokenChance;
    }

    public void Interact(InteractionBehaviour interactionBehaviour) {
        if (_destinationCounter.HasObject() || HUDManager.Instance.IsUiOpen) {
            return;
        }
        HUDManager.Instance.BuyItem(this, _objectToSell, _isBroken);
    }

    public void SkipItem() {
        _objectToSell = GetRandomObject();
        _isBroken = GetRandomBroken();
        HUDManager.Instance.UpdateItem(_objectToSell, _isBroken);
    }
    public void ConfirmBuy(ObjectSO objectSo, float price, bool isBroken) {
        _destinationCounter.SetItem(objectSo, price, isBroken);
        OnBuyItem?.Invoke(this, EventArgs.Empty);
        GameController.Instance.Money -= price;
        _objectToSell = GetRandomObject();
        _isBroken = GetRandomBroken();
        
    }

    public void SetItem(ObjectSO item, bool isBroken) {
        _objectToSell = item;
        _isBroken = isBroken;
        HUDManager.Instance.UpdateItem(_objectToSell, _isBroken);
    }
}
