attr = DS.attr
App.Order = DS.Model.extend
  state: attr('string')
  price: attr('number')

  list: DS.belongsTo('list', async: false)
  section: DS.belongsTo('section', async: false)
  product_orders: DS.hasMany('product_order', async: false)
  user: DS.belongsTo 'user', async: false

  active: (-> @get('state') == 'active').property('state')
  delivered: (-> @get('state') == 'delivered').property('state')
  placed: (-> @get('state') == 'placed').property('state')
  needs_supplier_attention: (-> (@get('state') is 'placed') or (@get('state') is 'active')).property('state')

  isClosed: ->
    @set 'state', 'closed'
  isCancelled: ->
    @set 'state', 'cancelled'
  isDelivered: ->
    @set 'state', 'delivered'
  isActive: ->
    @set 'state', 'active'
  mark_active: ->
    #$.post('/supplier/mark_order_in_process', order_id: id)
    Ember.$.post Routes.mark_in_process_suppliers_order_path @get('id')
    @isActive()
  mark_delivered: ->
    Ember.$.post Routes.mark_delivered_suppliers_order_path @get('id')
    @isDelivered()
  mark_cancelled: ->
    Ember.$.post Routes.cancel_suppliers_order_path @get('id')
    @isCancelled()
  total: (->
    @get('product_orders').getEach('total').reduce(((sum, total) -> sum + total), 0)
  ).property('product_orders.@each.total')

  display: Ember.computed 'product_orders.@each.display', ->
    @get('product_orders').map((po) -> po.get('display')).join(', ')

  display_with_table: (->
    table = t('models.table').toLowerCase()
    "#{@get('display')} #{table} #{@get('list.table.table_number')}".htmlSafe()
  ).property('display', 'list.table.table_number')

  display_tag: (->
    "<span class='display order-display order-#{@get('id')} #{@get('state')}'><span class='pre-display'></span>#{@get('display')}<span class='post-display'></span></span>".htmlSafe()
  ).property('display', 'state')
