App.modals.ProductCategoryMoveController = App.modals.BaseController.extend
  title_path: 'product_category.modal.move.title'
  actions:
    moveBelow: (below_product_category)->
      position = 0
      unless below_product_category
        @set 'model.position', position
        @get('model').save()
        position += 1
      for product_category in @get('product_categories')
        product_category.set('position', position)
        product_category.save()
        if below_product_category and product_category.id is below_product_category.id
          @set 'model.position', position += 1
          @get('model').save()
        position += 1

      @send 'close'

  product_categories: (->
    # do not return self, since place below should not include self option
    @store.peekAll('product_category').rejectBy('id', @get('model.id')).sortBy('position')
  ).property('model.id')

  sortableUpdate: (ids)->
    products = @get('model.products')
    ids.forEach (id, i)->
      if product = products.findProperty('id', id)
        #TODO: raise in frontend if product.get('isDirty'). Cannot modify position of product containing non persisted change
        product.set('position', i)
        product.save() if product.get('hasDirtyAttributes')
