using Kryz.CharacterStats.Examples;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VendorUI : MonoBehaviour
{
    public GameObject vendorUI;

    public List<VendorSlotUI> slots = new List<VendorSlotUI>();
    [SerializeField] private GameEvent onVendorUIClosed;
    [SerializeField] private GameEventListener_VendorData onVendorInteracted;
    [SerializeField] private GameEventListener onVendorReleased;

    private VendorData currentOpenVendor;

    private void Awake()
    {
        onVendorInteracted.Response.AddListener((vendorData) =>
        {
            OpenVendor(vendorData);
        });

        onVendorReleased.Response.AddListener(CloseVendor);

        Inventory.Instance.OnItemRightClickedEventWhileVendoring.AddListener(SellItem);

        vendorUI.SetActive(false);
    }

    private void InitializeVendorUI(VendorData vendorData)
    {
        for (int i = 0; i < slots.Count; i++)
        {
            slots[i].ClearSlot();
        }
        for (int i = 0; i < vendorData.items.Count; i++)
        {
            slots[i].AddItem(currentOpenVendor, vendorData.items[i]);
        }

    }

    public void OpenVendor(VendorData vendor)
    {
        currentOpenVendor = vendor;
        InitializeVendorUI(vendor);

        vendorUI.SetActive(true);

        Inventory.Instance.isVendoring = true;
        Inventory.Instance.OpenInventory();
    }

    public void CloseVendor()
    {
        vendorUI.SetActive(false);
        currentOpenVendor = null;

        Inventory.Instance.isVendoring = false;
        Inventory.Instance.CloseInventory();

        onVendorUIClosed.Raise();
    }

    private void SellItem(Item item)
    {
        if (Inventory.Instance.RemoveItem(item))
        {
            CoinBag.Instance.ChangeAmount(item.sellPricePlayer);
        }
    }
}
