attr = DS.attr
App.Section = DS.Model.extend
  title: attr 'string'
  width: attr 'number'
  height: attr 'number'
  tables: DS.hasMany('table', async: false)
  section_elements: DS.hasMany('section-element', async: false)
  section_areas: DS.hasMany('section-area', async: false)
  sorted_tables: Ember.computed 'tables.[]', -> @get('tables').sortBy('number')

  editmode: false

  arrange_tables_in_grid: (tables)->
    epsilon = 1e-10
    tables ||= @get('tables').sortBy('number')
    w = parseFloat(@get('width'))
    h = parseFloat(@get('height'))
    n = parseInt(tables.get('length'))
    unless w > 0 and h > 0 and n > 0
      console.log "Cannot arrange tables in grid since not all conditions are met"
      return false
    [lx, ly] = App.Distribution.distribute_lattice(w, h, n)
    return unless lx > 0 and ly > 0
    console.log "Distributing tables in grid using lx: #{lx}, ly: #{ly}"
    x0 = lx/2
    x = x0
    y = ly/2
    tables.forEach (table)->
      if x > w + (1e4*epsilon) # New row,  error = epsilon times possible tables in a row
        x = x0
        y += ly
      table.set 'position_x', x - table.get('width')/2 # Starting point of square + half the square (center) minus half the table size
      table.set 'position_y', y - table.get('height')/2
      x += lx
  arrange_tables_in_rows_of: (n, tables)->
    return false unless n
    n = parseInt(n)
    return false unless n > 0
    tables ||= @get('tables').sortBy('number')
    width = parseFloat(@get('width'))
    height = parseFloat(@get('height'))
    dx = width / n
    dy = height / Math.ceil(tables.get('length')/n)
    x = 0.0
    y = 0.0
    tables.forEach (table, i)->
      table.set 'position_x', x + (dx/2) - (table.get('width')/2)
      table.set 'position_y', y + (dy/2) - (table.get('height')/2)
      x += dx
      if (i + 1) % n  is 0
        x = 0.0
        y += dy
  arrange_tables_in_columns_of: (n, tables)->
    return false unless n
    n = parseInt(n)
    return false unless n > 0
    tables ||= @get('tables').sortBy('number')
    width = parseFloat(@get('width'))
    height = parseFloat(@get('height'))
    dx = width / Math.ceil(tables.get('length') / n)
    dy = height / n
    x = 0.0
    y = 0.0
    tables.forEach (table, i)->
      table.set 'position_x', x + (dx/2) - (table.get('width')/2)
      table.set 'position_y', y + (dy/2) - (table.get('height')/2)
      y += dy
      if (i + 1) % n  is 0
        y = 0.0
        x += dx
