98 lines
2.9 KiB
C#
98 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace YachtDice.Shop
|
|
{
|
|
public class ShopView : MonoBehaviour
|
|
{
|
|
[SerializeField] private Transform itemContainer;
|
|
[SerializeField] private ShopItemView itemPrefab;
|
|
[SerializeField] private TMP_Text currencyText;
|
|
[SerializeField] private Button closeButton;
|
|
[SerializeField] private ShopTooltipView tooltipView;
|
|
|
|
private readonly List<ShopItemView> _spawnedItems = new();
|
|
|
|
public event Action<IShopItem> OnBuyClicked;
|
|
|
|
private void Awake()
|
|
{
|
|
if (closeButton != null)
|
|
closeButton.onClick.AddListener(Hide);
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (closeButton != null)
|
|
closeButton.onClick.RemoveListener(Hide);
|
|
}
|
|
|
|
public void Show() => gameObject.SetActive(true);
|
|
public void Hide() => gameObject.SetActive(false);
|
|
public bool IsVisible => gameObject.activeSelf;
|
|
|
|
public void Populate(IReadOnlyList<IShopItem> catalog, ShopModel model)
|
|
{
|
|
ClearItems();
|
|
|
|
for (int i = 0; i < catalog.Count; i++)
|
|
{
|
|
var def = catalog[i];
|
|
if (def == null) continue;
|
|
|
|
var item = Instantiate(itemPrefab, itemContainer);
|
|
var state = model.GetItemState(def);
|
|
item.Setup(def, state);
|
|
item.OnBuyClicked += HandleBuy;
|
|
item.OnHoverEnter += HandleHoverEnter;
|
|
item.OnHoverExit += HandleHoverExit;
|
|
_spawnedItems.Add(item);
|
|
}
|
|
}
|
|
|
|
public void RefreshStates(IReadOnlyList<IShopItem> catalog, ShopModel model)
|
|
{
|
|
for (int i = 0; i < _spawnedItems.Count && i < catalog.Count; i++)
|
|
{
|
|
var state = model.GetItemState(catalog[i]);
|
|
_spawnedItems[i].SetState(state);
|
|
}
|
|
}
|
|
|
|
public void UpdateCurrencyDisplay(int currency)
|
|
{
|
|
if (currencyText != null)
|
|
currencyText.text = currency.ToString();
|
|
}
|
|
|
|
private void ClearItems()
|
|
{
|
|
for (int i = 0; i < _spawnedItems.Count; i++)
|
|
{
|
|
_spawnedItems[i].OnBuyClicked -= HandleBuy;
|
|
_spawnedItems[i].OnHoverEnter -= HandleHoverEnter;
|
|
_spawnedItems[i].OnHoverExit -= HandleHoverExit;
|
|
Destroy(_spawnedItems[i].gameObject);
|
|
}
|
|
_spawnedItems.Clear();
|
|
}
|
|
|
|
private void HandleBuy(IShopItem item) => OnBuyClicked?.Invoke(item);
|
|
|
|
private void HandleHoverEnter(IShopItem item, RectTransform anchor)
|
|
{
|
|
if (tooltipView != null)
|
|
tooltipView.Show(item, anchor);
|
|
}
|
|
|
|
private void HandleHoverExit()
|
|
{
|
|
if (tooltipView != null)
|
|
tooltipView.Hide();
|
|
}
|
|
}
|
|
}
|