App.TableController = Ember.Controller.extend
  orderTotal: (->
    @get('product_orders').getEach('total').reduce(((sum, total) -> sum + total), 0)
  ).property('product_orders.@each.quantity')

  actions:
    clearProductOrders: ->
      # toArray is needed because without is the iterator is not working properly
      @get('product_orders').toArray().invoke 'unloadRecord'
    orderProducts: ->
      orders = @get('product_orders').toArray()
      data = orders.map( (order)->order.serialize() )
      dataObject = {order: {}}
      for product_order in data
        dataObject['table_id'] = product_order.table_id
        dataObject['order'][product_order.product_id] = product_order.quantity
      $.ajax
        url: Routes.order_products_waiter_path(),
        type: "POST",
        data: JSON.stringify(dataObject),
        contentType: "application/json",
        dataType: 'json'
      orders.invoke 'unloadRecord'
