import { handleSuccess, handleFailure } from './assert-promise';

function applyData(object, data) {
  return new Ember.RSVP.Promise(function(resolve, reject) {
    if (typeof data === 'function') {
      var newObject = data.call(object, object);

      if (!newObject.then) {
        return resolve(newObject);
      } else {
        return newObject
          .catch(handleFailure('Failed to assemble data for model'))
          .then(resolve);
      }
    }

    var key, val, promiseList = [];

    for (key in data) {
      if (data.hasOwnProperty(key)) {
        val = data[key];

        if (typeof val === 'function') {
          val = val.call(object, object.get(key));

          if (val.then) {
            val = val.catch(handleFailure('Failed to apply attribute: ' + key));
            promiseList.push(val);
            continue;
          }
        }

        if (typeof val !== 'undefined') {
          object.set(key, val);
        }
      }
    }
    Ember.RSVP.Promise.all(promiseList).then(function() {
      resolve(object);
    });
  });
}

export default applyData;
export { applyData };

@@ -473,16 +473,25 @@
 ey, val,
+ related,
  promise
@@ -501,16 +501,16 @@
 t = %5B%5D;%0A
-
 %0A    for
@@ -700,16 +700,23 @@
  if (val
+ && val
 .then) %7B
@@ -828,24 +828,24 @@
 .push(val);%0A
-
             
@@ -871,24 +871,306 @@
  %7D%0A        %7D
+ else %7B%0A          related = (object.constructor %7C%7C %7B%7D).typeForRelationship && object.constructor.typeForRelationship(key);%0A          if (related && val.id && (val.fake %7C%7C val.local)) %7B%0A            val = object.store.createRecord(related.typeKey, %7Bid: val.id%7D);%0A          %7D%0A        %7D
 %0A%0A        if

Allow `{local: true, id: 123}` specification for relationships (inside `data` hash)