"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.lockChoices = exports.getShuffledChoices = exports.compact = void 0;

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _get = _interopRequireDefault(require("lodash/get"));

var _shuffle = _interopRequireDefault(require("lodash/shuffle"));

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

var _isNull = _interopRequireDefault(require("lodash/isNull"));

var _isUndefined = _interopRequireDefault(require("lodash/isUndefined"));

// eslint-disable-next-line no-console
var lg = function lg(n) {
  return console[n].bind(console, 'controller-utils:');
};

var debug = lg('debug');
var log = lg('log');
var warn = lg('warn');
var error = lg('error');

var compact = function compact(arr) {
  if (Array.isArray(arr)) {
    return arr.filter(function (v) {
      return !(0, _isNull["default"])(v) && !(0, _isUndefined["default"])(v);
    });
  }

  return arr;
};

exports.compact = compact;

var getShuffledChoices = function getShuffledChoices(choices, session, updateSession, choiceKey) {
  return new Promise(function (resolve) {
    var _session$data;

    log('updateSession type: ', (0, _typeof2["default"])(updateSession));
    log('session: ', session);
    var currentShuffled = compact((session === null || session === void 0 ? void 0 : (_session$data = session.data) === null || _session$data === void 0 ? void 0 : _session$data.shuffledValues) || (session === null || session === void 0 ? void 0 : session.shuffledValues) || []);

    if (!session) {
      // eslint-disable-next-line quotes
      warn("unable to save shuffled choices because there's no session.");
      resolve(undefined);
    } else if (!(0, _isEmpty["default"])(currentShuffled)) {
      var _session$data2;

      debug('use shuffledValues to sort the choices...', (_session$data2 = session.data) === null || _session$data2 === void 0 ? void 0 : _session$data2.shuffledValues);
      resolve(compact(currentShuffled.map(function (v) {
        return choices.find(function (c) {
          return c[choiceKey] === v;
        });
      })));
    } else {
      var shuffledChoices = (0, _shuffle["default"])(choices);

      if (updateSession && typeof updateSession === 'function') {
        try {
          //Note: session.id refers to the id of the element within a session
          var shuffledValues = compact(shuffledChoices.map(function (c) {
            return c[choiceKey];
          }));
          log('try to save shuffledValues to session...', shuffledValues);
          log('call updateSession... ', session.id, session.element);

          if ((0, _isEmpty["default"])(shuffledValues)) {
            error("shuffledValues is an empty array? - refusing to call updateSession: shuffledChoices: ".concat(JSON.stringify(shuffledChoices), ", key: ").concat(choiceKey));
          } else {
            updateSession(session.id, session.element, {
              shuffledValues: shuffledValues
            })["catch"](function (e) {
              return (// eslint-disable-next-line no-console
                console.error('update session failed for: ', session.id, e)
              );
            });
          }
        } catch (e) {
          warn('unable to save shuffled order for choices');
          error(e);
        }
      } else {
        warn('unable to save shuffled choices, shuffle will happen every time.');
      } //save this shuffle to the session for later retrieval


      resolve(shuffledChoices);
    }
  });
};
/**
 * If we return:
 * - true - that means that the order of the choices will be ordinal (as is created in the configure item)
 * - false - that means the getShuffledChoices above will be called and that in turn means that we either
 * return the shuffled values on the session (if any exists) or we shuffle the choices
 * @param model - model to check if we should lock order
 * @param session - session to check if we should lock order
 * @param env - env to check if we should lock order
 * @returns {boolean}
 */


exports.getShuffledChoices = getShuffledChoices;

var lockChoices = function lockChoices(model, session, env) {
  if (model.lockChoiceOrder) {
    return true;
  }

  log('lockChoiceOrder: ', (0, _get["default"])(env, ['@pie-element', 'lockChoiceOrder'], false));

  if ((0, _get["default"])(env, ['@pie-element', 'lockChoiceOrder'], false)) {
    return true;
  }

  var role = (0, _get["default"])(env, 'role', 'student');

  if (role === 'instructor') {
    // TODO: .. in the future the instructor can toggle between ordinal and shuffled here, so keeping this code until then

    /*const alreadyShuffled = hasShuffledValues(session);
     if (alreadyShuffled) {
      return false;
    }
     return true;*/
    return true;
  } // here it's a student, so don't lock and it will shuffle if needs be


  return false;
};

exports.lockChoices = lockChoices;
//# sourceMappingURL=persistence.js.map