DS.PromiseObject.reopen
  invoke: (method, args...) ->
    @then (object) -> object[method].apply(object, args)
DS.Model.reopen
  created_at: DS.attr('date')
  updated_at: DS.attr('date')
  #TODO: at the moment deleteRecord might work as expected, check this
  eraseRecord: ->
    @clearRelationships()
    @transitionTo('deleted.saved')
  #then: (callback) -> callback.call(@, @) DO NOT USE SINCE THERE IS TYPECHECKING ON .then in ember data https://github.com/emberjs/data/issues/2523
  invoke: (method, args...) ->
    @[method].apply(@, args)
DS.Model.reopenClass
  findCached: (id)->
    return null unless id
    @store.peekRecord(@typeKey, id)
  updateOrAdd: (attributes)->
    if cached = @findCached(attributes.id)

      # update relations if needed
      Ember.get(@, 'relationships').forEach (model, relation)=>
        relation = relation[0]
        if relation.kind == 'belongsTo'
          if id = attributes["#{relation.name}_id"]
            @store.findAll(relation.name, id).then (relation_object)->
              cached.set relation.name, relation_object
      cached.setProperties attributes
      cached
    else
      #@store.findRecord(@, attributes.id)
      @pushByAttriburtes(attributes)
  pushByAttriburtes: (attributes, options = {})->
    #store = @all().get('store')

    #Ugly hack at the cost of an extra request since I do not yet know the proper
    #code for adding a record by its attributes and having its associations set
    #@find(attributes.id)
    decamelized = Ember.String.decamelize(@typeKey)
    self_name = Ember.String.pluralize(decamelized)
    self_name = self_name.substr(1) if self_name[0] == '.'

    #belongs_tos = {}
    #Ember.get(@, 'relationships').forEach (model, relation)=>
      #relation = relation[0]
      #if relation.kind == 'belongsTo' and id = attributes["#{relation.name}_id"]
        #attributes[relation.name] = id unless attributes[relation.name]
        #belongs_tos[relation.name] = id

    nested_attributes = {}
    nested_attributes[self_name] = attributes
    # pushPayload makes association back references, just push not yet 2014-06-27
    new_record = @store.pushPayload(nested_attributes)

    #promises = []
    #association_names = []
    #Ember.get(@, 'relationships').forEach (model, relation)=>
      #relation = relation[0]
      #if relation.kind == 'belongsTo' and id = attributes["#{relation.name}_id"]
        #attributes[relation.name] = id
        #promises.push @store.findRecord(relation.name, id)
        #association_names.push relation.name
        #Ember.RSVP.all(promises).then (records)->
          #for record, i in records
            ##console.log "Setting relation #{relation.name} to #{record.get('id')}"
            #new_record.set association_names[i], record
        #attributes[relation.name] =
        #delete attributes["#{relation.name}_id"]
    #@createRecord attributes
