attr = DS.attr
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', async: true)
  is_paid: attr 'boolean'
  price: attr 'number'
  #has_active_orders: attr 'boolean'

  closed_at: DS.attr('date')
  users: DS.hasMany('user', async: false)
  #table_number: attr 'number'
  table: DS.belongsTo('table', inverse: 'active_list', async: true) # should be async, but synchroneously loading now fails with JSONAPI, this seems to work
  #users: DS.hasMany('user', inverse: 'active_list')
  orders: DS.hasMany('order', async: false)

  # COMPUTED PROPERTIES
  active: Ember.computed.equal 'state', 'active'
  total: (->
    @get('relevant_orders').getEach('total').reduce(((sum, total) -> sum + total), 0)
  ).property('relevant_orders.@each.total')
  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')
  sorted_orders: (-> @get('relevant_orders').sortBy('created_at').reverseObjects()).property('relevant_orders.[]')

  has_active_orders: (->
    return false unless @get('state') == 'active'
    !!@get('orders').filter( (order) -> order.get('state') is 'active' or order.get('state') is 'placed').length
  ).property('state', 'orders.@each.state')

  isClosed: ->
    @set('state', 'closed')
    #@set 'has_active_orders', false
    @set 'table', null
    @isHelped()
    @isPaid()

  # EVENTS
  isHelped: ->
    @set 'needs_help', false
  isNeedingHelp: ->
    @set 'needs_help', true
  isNeedingPayment: ->
    @set 'needs_payment', true
  isPaid: ->
    @set 'needs_payment', false

  # TRIGGERS
  close: ->
    @isClosed()
    $.post Routes.close_suppliers_list_path(@id)
  markHelped: ->
    @isHelped()
    $.post Routes.mark_helped_suppliers_list_path(@id)
  remove_needs_payment: ->
    @set 'needs_payment', false
    $.post Routes.remove_needs_payment_suppliers_list_path(@id)
