App.IndexController = Ember.ObjectController.extend
  needs: ['application']
  show_lists: true
  show_orders: true
  lists: (-> @store.all('list')).property()
  orders: (-> @store.all('order')).property()
  sections: (-> @store.all('section')).property()
  active_lists: (->
    if @get('controllers.application.active_section.id')
      lists = @get('lists').filter (l)=>( l.get('section.id') == @get('controllers.application.active_section.id') && l.get('state') == 'active' )
    else
      lists = @get('lists').filterProperty('state', 'active')
    lists.sortBy('created_at') # Not reversed, oldest on top, start with oldest order first :-) Customer happyness
  ).property('lists.@each.state', 'controllers.application.active_section.id')

  active_section: (-> @get('controllers.application.active_section')).property('controllers.application.active_section')
  active_orders: (->
    if @get('active_section.id')
      orders = @get('orders').filter (o)=>( o.get('section.id') == @get('active_section.id') && o.get('needs_supplier_attention') )
    else
      orders = @get('orders').filter (o)->( o.get('needs_supplier_attention') )
    orders.sortBy('created_at') # Not reversed, oldest on top, start with oldest order first :-) Customer happyness
  ).property('orders.@each.state', 'active_section.id')

  show_lists_table: Ember.computed 'show_lists', 'active_lists.@each', ->
    @get('show_lists') and @get('active_lists.length')
  show_orders_table: Ember.computed 'show_orders', 'active_orders.@each', ->
    @get('show_orders') and @get('active_orders.length')
  list_number_info: (-> " (#{@get('active_lists.length')})").property('active_lists.@each')
  order_number_info: (-> " (#{@get('active_orders.length')})").property('active_orders.@each')

  actions:
    ###
    markListAsHelped: (id)->
      if list = App.List.findCached(id)
        list.is_helped()

    closeList: (list)->
      @send 'openModal', 'modal_close_list', list
      # list.close()
    ###
    toggleDashboardLists: -> @set 'show_lists', !@get('show_lists')
    toggleDashboardOrders: ->@set 'show_orders', !@get('show_orders')

    markOrderDelivered: (id)->
      $.post('/supplier/order_is_delivered', order_id: id)
      if order = App.Order.findCached(id)
        order.set('state', 'delivered')

    markOrderActive: (id)->
      $.post('/supplier/mark_order_in_process', order_id: id)
      if order = App.Order.findCached(id)
        order.set('state', 'active')
    cancelOrder: (order)->
      $.post "/supplier/orders/#{order.id}/cancel"
      order.set 'state', 'cancelled'
    showList: (id)->
      @transitionToRoute 'list', id
