﻿nesterovskyBros.data.Products = nesterovskyBros.data.Model.define(
{

fields:
{
  productName: { type: "string", defaultValue: "Product Name" },
  productPrice: { type: "number", defaultValue: 10 },
  productUnitsInStock: { type: "number", defaultValue: 10 },
  products: { type: "default", defaultValue: [] }
},

addProduct: function () 
{
  this.get("products").push(
  {
    name: this.get("productName"),
    price: parseFloat(this.get("productPrice")),
    unitsInStock: parseFloat(this.get("productUnitsInStock"))
  });
},

deleteProduct: function (e) 
{
  var that = this;

  return nesterovskyBros.ui.Confirm.dialog(
  {
    dialog: { title: "Please confirm"  },
    message: "Do you want to delete the record?",
    confirm: "Yes",
    cancel: "No"
  }).
    open().
    center().
    result().
    then(
      function (confirmed)
      {
        if (!confirmed)
        {
          return;
        }

        // the current data item (product) is passed as the "data" field of the event argument
        var product = e.data;
        var products = that.get("products");
        var index = products.indexOf(product);

        // remove the product by using the splice method
        products.splice(index, 1);
      });
},

total: function () 
{
  return this.get("products").length;
},

totalPrice: function () 
{
  var sum = 0;

  $.each(
    this.get("products"), 
    function (index, product) { sum += product.price; });

  return sum;
},

totalUnitsInStock: function ()
{
  var sum = 0;

  $.each(
    this.get("products"), 
    function(index, product) { sum += product.unitsInStock; });

  return sum;
}

});

nesterovskyBros.ui.Products = nesterovskyBros.ui.UserControl.define(
{
  name: "Products",
  template: nesterovskyBros.templates.products,
  model: nesterovskyBros.data.Products
});