using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UIWidgets;
namespace UIWidgetsSamples.Shops {
///
/// On items change.
///
public delegate void OnItemsChange();
///
/// On money change.
///
public delegate void OnMoneyChange();
///
/// Trader.
///
public class Trader {
int money;
///
/// Gets or sets the trader money. -1 to infinity money
///
/// The money.
public int Money {
get {
return money;
}
set {
if (money==-1)
{
MoneyChanged();
return ;
}
money = value;
MoneyChanged();
}
}
ObservableList- inventory = new ObservableList
- ();
///
/// Gets or sets the inventory.
///
/// The inventory.
public ObservableList
- Inventory {
get {
return inventory;
}
set {
if (inventory!=null)
{
inventory.OnChange -= ItemsChanged;
}
inventory = value;
if (inventory!=null)
{
inventory.OnChange += ItemsChanged;
}
ItemsChanged();
}
}
///
/// The price factor.
///
public float PriceFactor = 1;
///
/// The delete items if Item.count = 0.
///
public bool DeleteIfEmpty = true;
///
/// Occurs when data changed.
///
public event OnItemsChange OnItemsChange;
///
/// Occurs when money changed.
///
public event OnMoneyChange OnMoneyChange;
///
/// Initializes a new instance of the class.
///
/// If set to true delete if empty.
public Trader(bool deleteIfEmpty = true)
{
DeleteIfEmpty = deleteIfEmpty;
inventory.OnChange += ItemsChanged;
}
void ItemsChanged()
{
if (OnItemsChange!=null)
{
OnItemsChange();
}
}
void MoneyChanged()
{
if (OnMoneyChange!=null)
{
OnMoneyChange();
}
}
///
/// Sell the specified order.
///
/// Order.
public void Sell(IOrder order)
{
if (order.OrderLinesCount()==0)
{
return ;
}
Inventory.BeginUpdate();
order.GetOrderLines().ForEach(SellItem);
Inventory.EndUpdate();
Money += order.Total();
}
///
/// Sells the item.
///
/// Order line.
void SellItem(IOrderLine orderLine)
{
var count = orderLine.Count;
// decrease items count
orderLine.Item.Count -= count;
// remove item from inventory if zero count
if (DeleteIfEmpty && (orderLine.Item.Count==0))
{
Inventory.Remove(orderLine.Item);
}
}
///
/// Buy the specified order.
///
/// Order.
public void Buy(IOrder order)
{
if (order.OrderLinesCount()==0)
{
return ;
}
Inventory.BeginUpdate();
order.GetOrderLines().ForEach(BuyItem);
Inventory.EndUpdate();
Money -= order.Total();
}
///
/// Buy the item.
///
/// Order line.
void BuyItem(IOrderLine orderLine)
{
// find item in inventory
var item = Inventory.Find(x => x.Name==orderLine.Item.Name);
var count = orderLine.Count;
// if not found add new item to inventory
if (item==null)
{
Inventory.Add(new Item(orderLine.Item.Name, count));
}
// if found increase count
else
{
item.Count += count;
}
}
///
/// Determines whether this instance can buy the specified order.
///
/// true if this instance can buy the specified order; otherwise, false.
/// Order.
public bool CanBuy(IOrder order)
{
return Money==-1 || Money>=order.Total();
}
}
}