'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = load;

var _Fetcher = require('../../../../util/Fetcher');

var _Fetcher2 = _interopRequireDefault(_Fetcher);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* global LearnosityApp */
var promise = void 0;
function load(quizSessionId) {
  if (!promise) {
    promise = new Promise(function (resolve, reject) {
      var learnosityURL = '//questions.learnosity.com/?v2';
      var addScript = document.createElement('script');
      addScript.setAttribute('src', learnosityURL);

      addScript.onload = function () {
        var f = new _Fetcher2.default();
        // TODO: Use async/await?
        f.post('/api/quiz_sessions/' + quizSessionId + '/learnosity_authentication?domain=' + window.location.host).then(function (response) {
          var questionsApp = LearnosityApp.init(response, {
            errorListener: function errorListener(e) {
              reject(e);
            },
            readyListener: function readyListener() {
              resolve(questionsApp);
            }
          });
        }).catch(function (e) {
          reject(e);
        });
      };

      document.body.appendChild(addScript);

      addScript.onerror = function (e) {
        reject(e);
      };
    });
  }
  return promise;
}