import RSVP from 'rsvp';
import run from 'ember-runloop';
import { RequestAbortedError } from 'web-client/utilities/error';

/**
 * Wraps an XHR object in a Promise.
 *
 * @param {XMLHttpRequest} xhr - The xhr object to wrap
 * @return {Promise}
 */
export default function xhrPromise(xhr) {
  return new RSVP.Promise(function(resolve, reject) {
    xhr.onload = (loadEvent) => run(() => {
      let request = loadEvent.target;
      if (requestStatusIsError(request.status)) {
        reject(loadEvent);
      } else {
        resolve(loadEvent);
      }
    });

    xhr.onerror = (...args) => run(() => reject(...args));
    xhr.onabort = () => run(() => reject(new RequestAbortedError()));
  });
}

function requestStatusIsError(status) {
  return status >= 400;
}
