Files

96 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using YachtDice.Dice;
using YachtDice.Economy;
using YachtDice.Inventory;
using YachtDice.Modifiers.Definition;
using YachtDice.Player;
namespace YachtDice.Shop
{
public class ShopModel
{
private readonly CurrencyBank _currencyBank;
private readonly InventoryModel _inventoryModel;
private readonly DiceCollection _diceCollection;
private readonly HashSet<string> _purchasedPermanentIds = new();
public event Action<IShopItem> OnItemPurchased;
public ShopModel(CurrencyBank currencyBank, InventoryModel inventoryModel, DiceCollection diceCollection)
{
this._currencyBank = currencyBank;
this._inventoryModel = inventoryModel;
this._diceCollection = diceCollection;
}
public bool CanPurchase(IShopItem item)
{
if (item == null) return false;
if (!_currencyBank.CanAfford(item.ShopPrice)) return false;
if (!item.IsRepurchasable && _purchasedPermanentIds.Contains(item.Id))
return false;
return true;
}
public bool TryPurchase(IShopItem item)
{
if (!CanPurchase(item)) return false;
if (!_currencyBank.Spend(item.ShopPrice)) return false;
if (!item.IsRepurchasable)
_purchasedPermanentIds.Add(item.Id);
switch (item)
{
case ModifierDefinition modifier:
_inventoryModel.AddModifier(modifier);
break;
case DiceDefinition dice:
_diceCollection.Add(dice);
break;
}
OnItemPurchased?.Invoke(item);
return true;
}
public bool IsPermanentOwned(string itemId) => _purchasedPermanentIds.Contains(itemId);
public ShopItemState GetItemState(IShopItem item)
{
if (item == null) return ShopItemState.TooExpensive;
if (!item.IsRepurchasable && _purchasedPermanentIds.Contains(item.Id))
return ShopItemState.Owned;
if (!_currencyBank.CanAfford(item.ShopPrice))
return ShopItemState.TooExpensive;
return item.IsRepurchasable
? ShopItemState.RepurchaseAvailable
: ShopItemState.Available;
}
public void LoadPurchasedPermanentIds(IEnumerable<string> ids)
{
_purchasedPermanentIds.Clear();
if (ids != null)
foreach (var id in ids) _purchasedPermanentIds.Add(id);
}
public HashSet<string> GetPurchasedPermanentIds() => new(_purchasedPermanentIds);
}
public enum ShopItemState
{
Available,
TooExpensive,
Owned,
RepurchaseAvailable,
}
}