"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createCorrectResponseSession = void 0;
exports.createDefaultModel = createDefaultModel;
exports.getScore = void 0;
exports.model = model;
exports.normalize = void 0;
exports.outcome = outcome;
exports.validate = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

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

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

var _defaults = _interopRequireDefault(require("./defaults"));

var _utils = require("./utils");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

// todo the import from pie-lib/rubric WILL break pslb
//  so don't use it unless you also test "yarn build"
var RUBRIC_TYPES = {
  SIMPLE_RUBRIC: 'simpleRubric',
  MULTI_TRAIT_RUBRIC: 'multiTraitRubric',
  'rubricless': 'rubricless'
};

function createDefaultModel() {
  var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return new Promise(function (resolve) {
    return resolve(_objectSpread(_objectSpread({}, _defaults["default"]), model));
  });
}

var normalize = function normalize(question) {
  return _objectSpread(_objectSpread({}, _defaults["default"]), question);
};
/**
 * @param {*} question
 * @param {*} session
 * @param {*} env
 */


exports.normalize = normalize;

function model(_x, _x2, _x3) {
  return _model.apply(this, arguments);
}

function _model() {
  _model = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(question, session, env) {
    var normalizedQuestion, _ref, scales, excludeZero, parsedScales;

    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            normalizedQuestion = normalize(question);

            if (!(normalizedQuestion.rubricType === RUBRIC_TYPES.SIMPLE_RUBRIC || normalizedQuestion.rubricType === RUBRIC_TYPES.RUBRICLESS)) {
              _context.next = 5;
              break;
            }

            return _context.abrupt("return", new Promise(function (resolve) {
              resolve(env && env.role && env.role === 'instructor' ? _objectSpread(_objectSpread({}, normalizedQuestion), {}, {
                rubrics: _objectSpread(_objectSpread({}, normalizedQuestion.rubrics), {}, {
                  multiTraitRubric: _objectSpread(_objectSpread({}, normalizedQuestion.rubrics.multiTraitRubric), {}, {
                    visible: false
                  })
                })
              }) : {});
            }));

          case 5:
            if (!env.role || env.role === 'student' && normalizedQuestion.rubrics && normalizedQuestion.rubrics.multiTraitRubric) {
              normalizedQuestion.rubrics.multiTraitRubric.visible = normalizedQuestion.visibleToStudent;
            } else {
              normalizedQuestion.rubrics.multiTraitRubric.visible = true;
            } // todo update pie-ui instead of parsing this here:


            _ref = normalizedQuestion.rubrics.multiTraitRubric || {}, scales = _ref.scales, excludeZero = _ref.excludeZero;
            parsedScales = (scales || []).map(function (scale) {
              return _objectSpread(_objectSpread({}, scale), {}, {
                excludeZero: excludeZero
              });
            });
            return _context.abrupt("return", _objectSpread(_objectSpread({}, normalizedQuestion), {}, {
              rubrics: _objectSpread(_objectSpread({}, normalizedQuestion.rubrics), {}, {
                simpleRubric: _objectSpread(_objectSpread({}, normalizedQuestion.rubrics.simpleRubric), {}, {
                  visible: false
                }),
                rubricless: _objectSpread(_objectSpread({}, normalizedQuestion.rubrics.rubricless), {}, {
                  visible: false
                }),
                multiTraitRubric: _objectSpread(_objectSpread({}, normalizedQuestion.rubrics.multiTraitRubric), {}, {
                  scales: parsedScales
                })
              })
            }));

          case 9:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _model.apply(this, arguments);
}

var getScore = function getScore() {
  return 0;
};
/**
 * @param {Object} model - the main model
 * @param {*} session
 * @param {Object} env
 */


exports.getScore = getScore;

function outcome() {
  return new Promise(function (resolve) {
    return resolve({
      score: 0,
      empty: true
    });
  });
}

var createCorrectResponseSession = function createCorrectResponseSession(question, env) {
  return new Promise(function (resolve) {
    if (env.mode !== 'evaluate' && env.role === 'instructor') {
      resolve({
        id: '1'
      });
    } else {
      resolve(null);
    }
  });
}; // IMPORTANT! This function is a duplicate of rubric/controller/validate function!
// If you make any changes to this function, please make sure you also update rubric/controller/validate function!“.


exports.createCorrectResponseSession = createCorrectResponseSession;

var validateSimpleRubric = function validateSimpleRubric(model) {
  var points = model.points;
  var errors = {};
  var pointsDescriptorsErrors = {};
  (points || []).forEach(function (point, index) {
    if (!point || point === '<div></div>') {
      pointsDescriptorsErrors[index] = 'Points descriptors cannot be empty.';
    } else {
      var identicalPointDescr = points.slice(index + 1).some(function (p) {
        return (0, _utils.markupToText)(p) === (0, _utils.markupToText)(point);
      });

      if (identicalPointDescr) {
        pointsDescriptorsErrors[index] = 'Points descriptors should be unique.';
      }
    }
  });

  if (Object.keys(pointsDescriptorsErrors).length > 0) {
    errors.pointsDescriptorsErrors = pointsDescriptorsErrors;
  }

  return errors;
}; // IMPORTANT! This function is a duplicate of multi-trait-rubric/controller/validate function!
// If you make any changes to this function, please make sure you also update multi-trait-rubric/controller/validate function!“.


var validateMultiTraitRubric = function validateMultiTraitRubric(model) {
  var scales = model.scales,
      _model$description = model.description,
      description = _model$description === void 0 ? false : _model$description,
      _model$pointLabels = model.pointLabels,
      pointLabels = _model$pointLabels === void 0 ? false : _model$pointLabels;
  var errors = {};
  var traitsErrors = {};
  var scorePointsErrors = {};
  (scales || []).forEach(function (scale, scaleIndex) {
    var _scale$traits = scale.traits,
        traits = _scale$traits === void 0 ? [] : _scale$traits;
    var _scale$scorePointsLab = scale.scorePointsLabels,
        scorePointsLabels = _scale$scorePointsLab === void 0 ? [] : _scale$scorePointsLab;
    var scaleErrors = {};
    var scorePointsLabelsErrors = {};

    if (pointLabels) {
      scorePointsLabels.forEach(function (scorePointLabel, scoreIndex) {
        if (!scorePointLabel || scorePointLabel === '<div></div>') {
          scorePointsLabelsErrors[scoreIndex] = 'Points labels should not be empty.';
        } else {
          var identicalScorePointLabel = scorePointsLabels.slice(scoreIndex + 1).some(function (s) {
            return (0, _utils.markupToText)(s) === (0, _utils.markupToText)(scorePointLabel);
          });

          if (identicalScorePointLabel) {
            scorePointsLabelsErrors[scoreIndex] = 'Points labels should be unique.';
          }
        }
      });
    }

    if (Object.keys(scorePointsLabelsErrors).length > 0) {
      scorePointsErrors[scaleIndex] = scorePointsLabelsErrors;
    }

    traits.forEach(function (trait, traitIndex) {
      if (!trait.name || trait.name === '<div></div>') {
        scaleErrors[traitIndex] = {
          name: 'Trait names should not be empty.'
        };
      } else {
        var identicalTraitName = traits.slice(traitIndex + 1).some(function (t) {
          return (0, _utils.markupToText)(t.name) === (0, _utils.markupToText)(trait.name);
        });

        if (identicalTraitName) {
          scaleErrors[traitIndex] = {
            name: 'Trait names should be unique.'
          };
        }
      }

      if (description && (!trait.description || trait.description === '<div></div>')) {
        scaleErrors[traitIndex] = _objectSpread(_objectSpread({}, scaleErrors[traitIndex]), {}, {
          description: 'Trait description should not be empty'
        });
      } else {
        var identicalTraitDescr = traits.slice(traitIndex + 1).some(function (t) {
          return (0, _utils.markupToText)(t.description) === (0, _utils.markupToText)(trait.description);
        });

        if (description && identicalTraitDescr) {
          scaleErrors[traitIndex] = _objectSpread(_objectSpread({}, scaleErrors[traitIndex]), {}, {
            description: 'Trait descriptions should be unique.'
          });
        }
      }
    });

    if (Object.keys(scaleErrors).length > 0) {
      traitsErrors[scaleIndex] = scaleErrors;
    }
  });

  if (Object.keys(traitsErrors).length > 0) {
    errors.traitsErrors = traitsErrors;
  }

  if (Object.keys(scorePointsErrors).length > 0) {
    errors.scorePointsErrors = scorePointsErrors;
  }

  return errors;
};

var validate = function validate() {
  var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _model$rubrics = model.rubrics,
      rubrics = _model$rubrics === void 0 ? {} : _model$rubrics,
      rubricType = model.rubricType;
  var _rubrics$multiTraitRu = rubrics.multiTraitRubric,
      multiTraitRubric = _rubrics$multiTraitRu === void 0 ? {} : _rubrics$multiTraitRu,
      _rubrics$simpleRubric = rubrics.simpleRubric,
      simpleRubric = _rubrics$simpleRubric === void 0 ? {} : _rubrics$simpleRubric;
  var errors = {};

  switch (rubricType) {
    case RUBRIC_TYPES.SIMPLE_RUBRIC:
    default:
      errors = validateSimpleRubric(simpleRubric);
      break;

    case RUBRIC_TYPES.MULTI_TRAIT_RUBRIC:
      errors = validateMultiTraitRubric(multiTraitRubric);
      break;
  }

  return errors;
};

exports.validate = validate;
//# sourceMappingURL=index.js.map