import RSVP from 'rsvp';
import run from 'ember-runloop';

const { Promise } = RSVP;

export default function injectScript(src) {
  return new Promise((resolve, reject) => {
    let script    = document.createElement('script');
    script.type   = 'text/javascript';
    script.async  = true;
    script.src    = src;
    script.onload = run.bind(null, () => {
      return resolve(script);
    });

    document.getElementsByTagName('head')[0].appendChild(script);

    script.addEventListener('error', (error) => {
      run(null, reject, error);
    });
  });
}
