attr = DS.attr
Qsupplier.App.List = DS.Model.extend
  state: attr 'string'
  needs_help: attr 'boolean'
  needs_payment: attr 'boolean'
  user_requests_closing: attr('boolean')
  users: DS.hasMany('user')
  is_paid: attr 'boolean'
  #has_active_orders: attr 'boolean'

  price: attr 'number'
  closed_at: DS.attr('date')
  #table_number: attr 'number'
  table: DS.belongsTo('table', inverse: 'active_list')
  #users: DS.hasMany('user', inverse: 'active_list')
  orders: DS.hasMany('order')
  section: DS.belongsTo('section')
  section_id: attr('string')
  active: ( -> @get('state') is 'active' ).property('state')
  markClosed: ->
    @set('state', 'closed')
    #@set 'has_active_orders', false
    @markHelped()
    @markIsPaid()
  markHelped: ->
    @set 'needs_help', false
  markNeedsHelp: ->
    @set 'needs_help', true
  markNeedsPayment: ->
    @set 'needs_payment', true
  markIsPaid: ->
    @set 'needs_payment', false
  relevant_orders: (-> @get('orders').filter((o)->o.get('state') isnt 'cancelled')).property('orders.@each.state')
  active_orders: (-> @get('orders').filter((o)->o.get('state') is 'placed' or o.get('state') is 'active')).property('orders.@each.state')

  total: (->
    @get('relevant_orders').getEach('total').reduce(((sum, total) -> sum + total), 0)
  ).property('relevant_orders.@each.total')
  has_active_orders: (->
    return false unless @get('state') == 'active'
    #!!@get('orders').filterProperty('state', 'active').length
    !!@get('orders').filter( (order) -> order.get('state') is 'active' or order.get('state') is 'placed').length
  ).property('state', 'orders.@each.state')
  close: ->
    @markClosed()
    $.post Routes.supplier_close_list_path(), list_id: @id

  is_helped: ->
    @markHelped()
    $.post Routes.supplier_mark_list_as_helped_path(), list_id: @id
  sorted_orders: (-> @get('relevant_orders').sortBy('created_at').reverseObjects()).property('relevant_orders.@each.isLoaded')
