App.ModalSectionAddTablesController = Ember.ObjectController.extend
  number_start: 100
  number_end: 110
  actions:
    close: ->
      @get('model.cancel').call(@) if @get('model.cancel')
      @send 'closeModal'
    confirm: ->
      @get('model.ok').call(@)
      @send 'closeModal'
    addTables: ->
      s = parseInt(@get('number_start'))
      e = parseInt(@get('number_end'))
      if e < s
        @set 'number_start', e
        @set 'number_end', s
        s = @get('number_start')
        e = @get('number_end')

      Ember.$.post Routes.add_tables_suppliers_section_path(@get('model.id')),
        number_start: s
        number_end: e
      , (result,state,xhr)=>
        #@store.pushPayload 'table', result
        @store.pushPayload result
        @send 'close'

        #TODO remove followin code if Ember pushPayload is working
        #properly with associations
        section_id = @get('model.id')
        tables_that_should_be_in_section = @store.all('table').filter((t)->t.get('section.id') == section_id)
        current_table_ids = @get('model.tables').mapProperty('id')
        for table in tables_that_should_be_in_section.toArray()
          @get('model.tables').pushObject(table) unless table.get('id') in current_table_ids
        #TODO it still does not work for the second client side action,
        #soo the good old reload for now for the failing case
        window.location.reload() if result.tables.length != tables_that_should_be_in_section.toArray().length
        return


