App.ApplicationRoute = Ember.Route.extend
  setupController: (controller)->
    #@controllerFor('product_orders').set 'model', @store.filter('product_order', (po)-> !po.get('order')) # does not work (yet)
    #@controllerFor('product_orders').set 'model', @store.filter('product_order', (po)-> !po.get('id'))
    controller.secured ->
      faye = new Faye.Client($event_host)
      user_id = Qstorage.getItem('user_id')
      faye.subscribe "/user/"+user_id, (e)=>
        console.log e
        @events[e.event].call(@, e.data) if @events[e.event]
      @setCurrentList()

  unauthorized: ->
    Qstorage.removeItem('auth_token')
    Qstorage.removeItem('user_id')
    @set 'globals.active_list', null
    #@send 'obtain_token'
    @controllerFor('application').redirect_to 'sign_in', message: 'unauthorized'

  handleAuthInfo: (user_id, auth_token)->
    Qstorage.setItem 'user_id', user_id
    Qstorage.setItem 'auth_token', auth_token
    controller = @controllerFor('application')
    controller.setCurrentList ->
      @transitionTo('active_list')
      controller.set 'globals.notice', t('messages.authenticated')
  actions:
    obtain_token: ( options = {} ) ->
      provider = options.provider || 'facebook'
      auth_win = window.open "#{$obtain_token_url}?provider=#{provider}", "_blank", "location=no"
      auth_win.addEventListener "loadstart", (event)=>
        if event.url.match 'close_window'
          user_id = event.url.match(/user_id=([\w+-]+)/)[1]
          auth_token = event.url.match(/authentication_token=([\w-]+)/)[1]
          @handleAuthInfo(user_id, auth_token)
          auth_win.close()
      true
    #openModal: (modalName, model)->
    #  @controllerFor(modalName).set('model', model)
    #  @render modalName,
    #    into: 'application'
    #    outlet: 'modal'
    #closeModal: ->
    #  @disconnectOutlet
    #    outlet: 'modal'
    #    parentView: 'application'
    openModal: (modalName, options={})->
      controller_name = options.controller || modalName
      try
        controller =  @controllerFor("modals/#{modalName}")
      catch error
        controller = @controllerFor("modals/base")
      controller ||= @controllerFor("modals/base")
      controller.set 'model', options.model
      defaultModalOptions =
        closeOnOverlay: true
        closeOnModalClick: false
      controller.set 'modal_options', Ember.Object.create($.extend(defaultModalOptions, options))
      @render "modals/#{modalName}",
        into: 'application'
        outlet: 'modal'
        view: 'modal'
        controller: controller

    closeModal: ->
      @disconnectOutlet
        outlet: 'modal'
        parentView: 'application'

    confirm: (options = {})->
      options.model ||= Ember.Object.create()
      @send 'openModal', 'confirm', options
    sendFeedback: (feedback, callback)->
      return unless feedback
      $.post $user_feedback_path, feedback: feedback, callback

    listNeedsPayment: ->
      @get('controller').secured ->
        @set 'globals.active_list.needs_payment', true
        Ember.$.post "#{$data_host}/user/list_needs_payment.json"
        #Ember.$.post("#{$data_host}/user/list_needs_payment.json").then (res) =>
          #@set('list.needs_payment', true) # also done by faye
    listNeedsHelp: ->
      @get('controller').secured ->
        @set 'globals.active_list.needs_help', true
        Ember.$.post "#{$data_host}/user/needs_help.json"
        #Ember.$.post("#{$data_host}/user/needs_help.json").then (res) =>
          #@set('list.needs_help', true) # also done by faye
    error: (error, transition, klass)->
      message = null
      if error.status is 404
        if klass.routeName is 'table'
          message = t('errors.404.model.message', model: t("models.#{klass.routeName}"), id: transition.state.params.table.table_id)
        else
          message = t('errors.404.general.message')
      @transitionTo('index').then (route)->
        #route.get('controller.controllers.application').set 'notice', message if route and route.get
        route.set 'globals.notice', message if route and route.set
        $log
          action: 'applicationerror'
          error: error.message
    selectQr: (table)->
      @get('controller').secured ->
        appcontroller = @
        $.getJSON( "#{$data_host}/user/table_info.json?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', res.table)
                  body: t('move_table.confirmation_body', res.table)
                  ok: =>
                    Ember.$.post "#{$data_host}/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
        , (error)->
          if error.status is 404
            message = 'table_not_found'
          else
            message = 'general_error'
          appcontroller.redirect_to 'index', message: message
    scanQr: ->
      return @transitionTo('sign_in') unless Qstorage.getItem('auth_token')
<% if Rails.env.user_app? %>
      ar = @
      scanner = cordova.require("cordova/plugin/BarcodeScanner")
      @transitionTo('scanning').then ->
        scanner.scan (result)->
          if result.cancelled
            ar.transitionTo('index')
            $log
              action: 'qrscan'
              result: 'cancel'
          else
            table_id_index = result.text.indexOf('s?t=');
            if table_id_index > -1
              table_id = result.text.substr(table_id_index + 4);
              # ar.transitionTo 'table', table_id
              # ar.actions.selectQr.call(ar, table: {_id: table_id})
              ar.send('selectQr', _id: table_id)
            else
              ar.transitionTo('index').then (route)->
                #route.get('controller.controllers.application').set 'notice',  "we got a barcode: '#{result.text}' but cannot extract a table id"
                route.set 'globals.notice',  "we got a barcode: '#{result.text}' but cannot extract a table id"
              $log
                action: 'qrscan'
                error: 'cannot extract table id'
                info: result.text

        , (error)->
          $log
            action: 'qrscan'
            error: 'scan failed'
            info: error
          ar.transitionTo('index').then (route)->
            #route.get('controller.controllers.application').set 'notice',  "scanning failed: #{error}"
            route.set 'globals.notice',  "scanning failed: #{error}"
<% else %>
      @transitionTo 'select_qrcode'
<% end %>
