App.NewProductOrdersListComponent = Ember.Component.extend
  orderTotal: (->
    #Math.round(Math.random()*100)
    @get('product_orders').getEach('total').reduce(((sum, total) -> sum + total), 0)
  ).property('product_orders.@each.quantity')
  all_product_orders: Ember.computed -> @store.peekAll('product_order')
  product_orders: Ember.computed 'all_product_orders.@each.isNew', -> @get('all_product_orders').filterBy('isNew')
  #product_orders: (->@get('model')).property('model')
  #product_orders: -> @store.peekAll('product_order')
  showTotal: (-> if @get('product_orders.length') && @get('product_orders.length') > 1 then true else false ).property('product_orders.length')
  actions:
    # clearProductOrders: ->
    #   #TODO: make clearing of unpersisted product orders
    #   @get('product_orders').invoke 'eraseRecord'
    orderProducts: ->
      # table = @get('controllers.table.model')
      # list = @get('globals.active_list')
      # order = @store.createRecord('order', list: list, table: table)
      # new_product_orders = @store.all('product_order').filterProperty('order', null)
      # order.get('product_orders').pushObjects(new_product_orders)
      #
      # order.save().then (response)=>
      #   new_product_orders.invoke 'eraseRecord'
      #   if @get('globals.active_list')
      #     @transitionToRoute 'active_list'
      #   else
      #     # Get list info from the server
      #     @get('controllers.application').setCurrentList ->
      #       @transitionToRoute 'active_list'
      # , @ajaxError (jqXHR)=>
      #   new_product_orders.invoke 'eraseRecord'
      #   @redirect_to 'user_root',  message: 'order_could_not_be_processed'

      #orders = @store.all('product_order').toArray()
      #data = @get('product_orders').map( (po)->po.serialize() )
      dataObject = {table_id: @get('table.id')}
      dataObject.product_orders = @get('product_orders').map( (po) -> po.serialize()).toArray()
      #@get('product_orders').forEach (product_order)-> dataObject['order'][product_order.get('product.id')] = product_order.get('quantity')
      Ember.$.ajax
        type: 'POST'
        dataType: 'json'
        contentType: 'application/json'
        url: "#{$data_host}/user/orders.json"
        data: JSON.stringify(dataObject)
        success: (response) =>
          @store.pushPayload(order: response.order) if response.order
      @get('reference_controller').transitionToRoute 'active_list'
      @get('product_orders').invoke 'unloadRecord'

    removeProductOrder: (product_order)->
      product_order.eraseRecord()
