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: ->
    @store.findAll 'panda/workflow-instance-type'
    @store.findAll 'panda/organization'
    @store.findAll 'user'
    @store.findAll 'panda/tracker-subject'
    @set 'router.globals.adapters', @store.findAll 'panda/adapter'
    #Ember.RSVP.all([
    #  @store.findAll 'workflow-instance-type'
    #  @store.findAll 'organization'
    #  @store.findAll 'user'
    #  @store.findAll 'tracker-subject'
    #]).then =>
    #  @set 'router.globals.preload_resources_fulfilled', true

  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

