App.SelectQrcodeController = Ember.Controller.extend
  actions:
    selectQr: (table)->
      @secured ->
        $.getJSON($data_host + '/user/table_info.json?'+@authentication_string+'&table_id='+table._id).then (res)=>
          if res.current_table_id
            if res.other_supplier
              @redirect_to 'user_root', message: 'table_is_from_other_supplier'
            else if res.current_table_id == table._id
              #nothing has changed, show product list
              @redirect_to 'table', table._id
            else if res.current_table_id != table._id
              if res.occupied
                @redirect_to 'user_root', message: 'table_is_occupied'
              else if res.reserved
                @redirect_to 'user_root', message: 'table_is_reserved'
              else if table.closed
                @redirect_to 'user_root', message: 'table_is_closed'
              else if res.supplier_closed
                @redirect_to 'user_root', message: 'supplier_is_closed'
              else
                ## Offer to move table
                @send 'confirm',
                  title: t('move_table.confirmation_title')
                  body: t('move_table.confirmation_body')
                  ok: =>
                    Ember.$.post '/user/move_table.json', table_id: table._id, (res2)=>
                      if res2.occupied
                        @redirect_to 'user_root', message: 'move_table.cannot_move_to_occupied_tabe'
                      else
                        # Now we can move table
                        Qstorage.setItem 'table_id', table._id
                        @redirect_to 'table', table._id, message: 'move_table.moved_to_another_table'
                  cancel: =>
                    @redirect_to 'table', res.current_table_id
          else
            @redirect_to 'table', table._id
