'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.qtiFileUpload = exports.postQtiCreate = exports.pollForQtiInfo = exports.getQTIInfo = undefined;

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

var _Fetcher2 = _interopRequireDefault(_Fetcher);

var _constants = require('../../constants');

var _callHandlers = require('../../common/api/callHandlers');

var _quizzes = require('../../common/api/quizzes');

var _fileUpload = require('../../common/api/fileUpload');

var _banks = require('../../banks/api/banks');

var _upload = require('../../common/actions/upload');

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

var getQTIInfo = exports.getQTIInfo = function getQTIInfo(quizId) {
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default();

    var url = '/api/quizzes/' + quizId + '/qti_imports';
    var addImportsToStore = function addImportsToStore(importsList) {
      dispatch((0, _callHandlers.handleQtiImportsResponse)(importsList));
    };

    return fetcher.get(url).then(addImportsToStore);
  };
};

var pollForQtiInfo = exports.pollForQtiInfo = function pollForQtiInfo(parentId, parentType) {
  var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { getExistingBankAndEntries: _banks.getExistingBankAndEntries, getExistingQuizAndItems: _quizzes.getExistingQuizAndItems, pollForQtiInfo: pollForQtiInfo };

  return function (dispatch, getState) {
    return new Promise(function (resolve, reject) {
      setTimeout(function () {
        var fetcher = new _Fetcher2.default();

        var url = void 0;
        if (parentType === _constants.PARENT_TYPE_QUIZ) {
          url = '/api/quizzes/' + parentId + '/qti_imports';
        } else {
          url = '/api/banks/' + parentId + '/qti_imports';
        }
        var addImportsToStore = function addImportsToStore(importsList) {
          dispatch((0, _callHandlers.handleQtiImportsResponse)(importsList));
          if (importsList.find(function (qtiImport) {
            return qtiImport.status === 'completed';
          })) {
            if (parentType === _constants.PARENT_TYPE_QUIZ) {
              dispatch(opts.getExistingQuizAndItems(parentId));
            } else {
              dispatch(opts.getExistingBankAndEntries(parentId));
            }
            dispatch((0, _upload.uploadStatus)(_constants.FILE_UPLOAD_SUCCESS));
          } else if (importsList.find(function (qtiImport) {
            return qtiImport.status !== 'failed';
          })) {
            dispatch(opts.pollForQtiInfo(parentId, parentType, opts));
          } else {
            dispatch((0, _upload.uploadStatus)(_constants.FILE_UPLOAD_FAILURE));
          }
        };

        return fetcher.get(url).then(addImportsToStore).then(resolve);
      }, 2000);
    });
  };
};

// =====================
//   UPLOAD A QTI FILE
// =====================

// This fxn is curried twice to allow for setting the creation url, then for receiving
// the url from the first response, and finally receives the promise.
// Exported for testing purposes
var postQtiCreate = exports.postQtiCreate = function postQtiCreate(qtiImportUrl, dispatch, onError) {
  return function (url) {
    var qtiCreateFetcher = new _Fetcher2.default({
      callType: _constants.CREATE_QTI_IMPORT,
      onError: onError
    });

    var requestBody = JSON.stringify({ url: url });

    var addImportToStore = function addImportToStore(importData) {
      dispatch((0, _callHandlers.handleQtiImportsResponse)([importData]));
      var parentType = importData.parent_type === 'Quiz' ? _constants.PARENT_TYPE_QUIZ : _constants.PARENT_TYPE_BANK;
      dispatch(pollForQtiInfo(importData.parent_id, parentType));
    };

    return qtiCreateFetcher.post(qtiImportUrl, { body: requestBody }).then(addImportToStore);
  };
};

var qtiFileUpload = exports.qtiFileUpload = function qtiFileUpload(file, parentId, parentType, onError) {
  var withUrlCallback = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _fileUpload.sendFileToS3;
  var qtiCreateFxn = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : postQtiCreate;

  return function (dispatch, getState) {
    var qtiImportUrl = void 0;
    if (parentType === _constants.PARENT_TYPE_QUIZ) {
      qtiImportUrl = '/api/quizzes/' + parentId + '/qti_imports';
    } else {
      qtiImportUrl = '/api/banks/' + parentId + '/qti_imports';
    }
    var pathToGetUrl = qtiImportUrl + '/upload_url';
    var onSuccess = qtiCreateFxn(qtiImportUrl, dispatch, onError);

    return (0, _fileUpload.getUploadUrl)(pathToGetUrl).then(withUrlCallback(file, onSuccess, onError));
  };
};