import Ember from 'ember'
import DunlopApplicationRoute from 'ember-cli-dunlop/mixins/application-route'

export default Ember.Route.extend DunlopApplicationRoute,
  # this method gets fired after a successful authentication or successful fetch of current user through
  # HTTP session or ember-simple-auth session
  current_user_loaded: (user) ->
    @_super arguments...
    @preloadResources()

  #setupController: (controller)->
  #  host = @store.adapterFor('application').host || ''
  #  event_host = "#{host}/faye"
  #  faye = new Faye.Client(event_host)
  #  faye.subscribe '/activity', (data)=>
  #    return if data.client_id is window.client_id # prevent duplicate records with same id, still an issue in ember 2.9.0/1
  #    console.log data
  #    switch data.event
  #      when 'payload'
  #        data.payload = JSON.parse(data.payload) if typeof(data.payload) is 'string'
  #        @store.pushPayload(data.payload)
  #      when 'destroy'
  #        if record = @store.peekRecord(data.model, data.id)
  #          record.rollbackAttributes()
  #          record.unloadRecord()

  preloadResources: ->
    Ember.RSVP.all([
      @store.findAll 'panda/workflow-instance-type'
      @store.findAll 'panda/organization'
      @store.findAll 'user'
      @store.findAll 'panda/tracker-subject'
      @store.findAll 'panda/adapter'
      @store.query('dunlop/user-filter', q: {scope_key_matches: 'panda/%'})
      @load_backend_settings()
    ]).catch((reason) =>
      @get('initial_resources_reject')(reason)
    ).then (results...) =>
      @set 'router.globals.adapters', results[4] #.content ? this is a promise, could be an array @store.peekAll('panda/adapter')
      @get('initial_resources_resolve')()

  load_backend_settings: ->
    session = @get('session')
    url = "#{config.apiHost}/#{config.apiNamespace}/settings"
    success = (settings) =>
      # iterate for data bindings (environment)
      return unless settings.data?
      for setting in settings.data
        @set "router.globals.#{setting.id}", setting.attributes.value
      #Ember.assign @get('router.globals'), settings
      window.app_globals = @get('router.globals')
    request =
      url: url
      type: 'GET'
      contentType: "application/json"
      success: success
      dataType: "json"
    if get(session, 'isAuthenticated')
      session.authorize 'authorizer:devise', (key, authorization) ->
        request.crossDomain = true
        request.headers = {"#{key}": authorization}
    Ember.$.ajax request

  actions:
    debug: -> debugger
    dateSort: (attribute, a, b) ->
      date_a = Ember.get(a, attribute)
      date_b = Ember.get(b, attribute)
      return 0 if date_a is date_b
      return 1 unless date_b
      return -1 unless date_a
      date_a_string = date_a.toISOString()
      date_b_string = date_b.toISOString()
      if  date_a_string > date_b_string
        return 1
      else if  date_a_string < date_b_string
        return -1
      0

