App.ModalSectionArrangeTablesController = Ember.ObjectController.extend
  alert_message: null
  arrange_type: 'distributed' # can be distributed, by_row or by_column
  row_count: 2
  column_count: 2
  isDistributed: (->@get('arrange_type') is 'distributed').property('arrange_type')
  isByRow: (->@get('arrange_type') is 'by_row').property('arrange_type')
  isByColumn: (->@get('arrange_type') is 'by_column').property('arrange_type')
  actions:
    close: ->
      @get('model.cancel').call(@) if @get('model.cancel')
      @send 'closeModal'
    confirm: ->
      @get('model.ok').call(@)
      @send 'closeModal'
    arrangeTables: ->
      Ember.$.post Routes.arrange_tables_suppliers_section_path(@get('model.id')),
        option: @get('arrange_type')
        row_count: @get('row_count')
        column_count: @get('column_count')
      , (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
    makeDistributed: -> @set 'arrange_type', 'distributed'
    makeByRow: -> @set 'arrange_type', 'by_row'
    makeByColumn: -> @set 'arrange_type', 'by_column'
