﻿using UnityEngine;

public class ShopController : Singleton<ShopController>
{
	[SerializeField]
	private DataBindContext m_DataBindContext;
	private ShopProduct[] m_Products;

	private void Awake()
	{
		m_Products = Resources.LoadAll<ShopProduct>("Data/Products");
	}

	private void Start()
	{
		var consumables = new ObservableList("consumables");
		var upgrades = new ObservableList("upgrades");

		for (var i = 0; i < m_Products.Length; i++) {
			var product = m_Products[i];

			switch (product.category) {
				case ShopProduct.Category.Consumable:
					consumables.Add(product);
					break;
				case ShopProduct.Category.Upgrade:
					upgrades.Add(product);
					break;
			}
		}

		m_DataBindContext["consumables"] = consumables;
		m_DataBindContext["upgrades"] = upgrades;
	}

	private new void OnEnable()
	{
		base.OnEnable();

		m_DataBindContext.BindAll();
	}

	public bool CanBuy(ShopProduct product)
	{
		return GameData.instance.coins >= product.price;
	}

	public void Buy(ShopProduct product)
	{
		if (!CanBuy(product)) {
			return;
		}

		GameData.instance.coins -= product.price;
		m_DataBindContext["coins"] = GameData.instance.coins;
	}
}