"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.RubricType = exports.RawAuthoring = exports.PointConfig = void 0;

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

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

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

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

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

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

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

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

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

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _styles = require("@material-ui/core/styles");

var _classnames = _interopRequireDefault(require("classnames"));

var _OutlinedInput = _interopRequireDefault(require("@material-ui/core/OutlinedInput"));

var _InputLabel = _interopRequireDefault(require("@material-ui/core/InputLabel"));

var _Select = _interopRequireDefault(require("@material-ui/core/Select"));

var _FormControl = _interopRequireDefault(require("@material-ui/core/FormControl"));

var _MenuItem = _interopRequireDefault(require("@material-ui/core/MenuItem"));

var _times = _interopRequireDefault(require("lodash/times"));

var _Checkbox = _interopRequireDefault(require("@material-ui/core/Checkbox"));

var _FormGroup = _interopRequireDefault(require("@material-ui/core/FormGroup"));

var _FormControlLabel = _interopRequireDefault(require("@material-ui/core/FormControlLabel"));

var _grey = _interopRequireDefault(require("@material-ui/core/colors/grey"));

var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));

var _DragIndicator = _interopRequireDefault(require("@material-ui/icons/DragIndicator"));

var _editableHtml = _interopRequireDefault(require("../editable-html"));

var _reactBeautifulDnd = require("react-beautiful-dnd");

var _debug = _interopRequireDefault(require("debug"));

var _takeRight = _interopRequireDefault(require("lodash/takeRight"));

var _pointMenu = _interopRequireDefault(require("./point-menu"));

var _range = _interopRequireDefault(require("lodash/range"));

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; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var log = (0, _debug["default"])('pie-lib:rubric:authoring');

var reorder = function reorder(list, startIndex, endIndex) {
  var result = Array.from(list);

  var _result$splice = result.splice(startIndex, 1),
      _result$splice2 = (0, _slicedToArray2["default"])(_result$splice, 1),
      removed = _result$splice2[0];

  result.splice(endIndex, 0, removed);
  return result;
};

var RubricType = _propTypes["default"].shape({
  excludeZero: _propTypes["default"].bool,
  points: _propTypes["default"].arrayOf(_propTypes["default"].string),
  sampleAnswers: _propTypes["default"].arrayOf(_propTypes["default"].string),
  maxPoints: _propTypes["default"].number
});

exports.RubricType = RubricType;
var MaxPoints = (0, _styles.withStyles)(function (theme) {
  return {
    formControl: {
      minWidth: '120px',
      margin: theme.spacing.unit
    }
  };
})(function (props) {
  var value = props.value,
      _onChange = props.onChange,
      max = props.max,
      classes = props.classes;
  return /*#__PURE__*/_react["default"].createElement(_FormControl["default"], {
    className: classes.formControl,
    variant: "outlined"
  }, /*#__PURE__*/_react["default"].createElement(_InputLabel["default"], {
    width: 100,
    htmlFor: "..."
  }, "Max Points"), /*#__PURE__*/_react["default"].createElement(_Select["default"], {
    value: value,
    onChange: function onChange(e) {
      return _onChange(e.target.value);
    },
    input: /*#__PURE__*/_react["default"].createElement(_OutlinedInput["default"], {
      labelWidth: 80
    })
  }, (0, _range["default"])(1, max).map(function (v) {
    return /*#__PURE__*/_react["default"].createElement(_MenuItem["default"], {
      key: "".concat(v),
      value: v
    }, v);
  })));
}); // if the value is null or 'null', the Sample Answer input field for that point will not be dispalyed
// if the value is '', the Sample Answer input field will be empty

var checkSampleAnswer = function checkSampleAnswer(sampleAnswer) {
  return sampleAnswer === null || sampleAnswer === 'null';
};

var PointConfig = (0, _styles.withStyles)(function (theme) {
  return {
    pointConfig: {},
    row: {
      display: 'flex',
      width: '100%',
      position: 'relative'
    },
    editor: {
      width: '100%',
      backgroundColor: "".concat(theme.palette.common.white, " !important")
    },
    dragIndicator: {
      paddingTop: theme.spacing.unit,
      color: _grey["default"][500]
    },
    pointsLabel: {
      color: _grey["default"][500],
      paddingBottom: theme.spacing.unit,
      textTransform: 'uppercase'
    },
    sampleAnswersEditor: {
      paddingLeft: theme.spacing.unit * 3
    },
    pointMenu: {
      position: 'absolute',
      right: 0
    }
  };
})(function (props) {
  var points = props.points,
      content = props.content,
      classes = props.classes,
      sampleAnswer = props.sampleAnswer,
      _props$mathMlOptions = props.mathMlOptions,
      mathMlOptions = _props$mathMlOptions === void 0 ? {} : _props$mathMlOptions;
  var pointsLabel = "".concat(points, " ").concat(points <= 1 ? 'pt' : 'pts');
  var showSampleAnswer = checkSampleAnswer(sampleAnswer);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.pointConfig
  }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    variant: "overline",
    className: classes.pointsLabel
  }, pointsLabel), /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.row
  }, /*#__PURE__*/_react["default"].createElement(_DragIndicator["default"], {
    className: classes.dragIndicator
  }), /*#__PURE__*/_react["default"].createElement(_editableHtml["default"], {
    className: classes.editor,
    markup: content,
    onChange: props.onChange,
    mathMlOptions: mathMlOptions
  }), /*#__PURE__*/_react["default"].createElement(_pointMenu["default"], {
    classes: {
      icon: classes.pointMenu
    },
    showSampleAnswer: showSampleAnswer,
    onChange: props.onMenuChange
  })), !showSampleAnswer && /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.sampleAnswersEditor
  }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    variant: "overline",
    className: classes.dragIndicator
  }, "Sample Response"), /*#__PURE__*/_react["default"].createElement(_editableHtml["default"], {
    className: classes.editor,
    markup: sampleAnswer,
    onChange: props.onSampleChange,
    mathMlOptions: mathMlOptions
  })));
});
exports.PointConfig = PointConfig;

var RawAuthoring = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(RawAuthoring, _React$Component);

  var _super = _createSuper(RawAuthoring);

  function RawAuthoring() {
    var _this;

    (0, _classCallCheck2["default"])(this, RawAuthoring);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "dragEnd", function (result) {
      if (!result.destination) {
        return;
      }

      var _this$props = _this.props,
          value = _this$props.value,
          onChange = _this$props.onChange;
      var points = reorder(value.points, result.source.index, result.destination.index);
      var sampleAnswers = reorder(value.sampleAnswers, result.source.index, result.destination.index);
      onChange(_objectSpread(_objectSpread({}, value), {}, {
        points: points,
        sampleAnswers: sampleAnswers
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeMaxPoints", function (maxPoints) {
      var _this$props2 = _this.props,
          value = _this$props2.value,
          onChange = _this$props2.onChange;
      var currentMax = value.points.length - 1;
      log('current', currentMax, 'new: ', maxPoints);
      var points, sampleAnswers;

      if (maxPoints > currentMax) {
        points = (0, _times["default"])(maxPoints - currentMax).map(function () {
          return '';
        }).concat(value.points);
        sampleAnswers = (0, _times["default"])(maxPoints - currentMax).map(function () {
          return null;
        }).concat(value.sampleAnswers);
      }

      if (maxPoints < currentMax) {
        log('less than');
        points = (0, _takeRight["default"])(value.points, maxPoints + 1);
        sampleAnswers = (0, _takeRight["default"])(value.sampleAnswers, maxPoints + 1);
      }

      if (points) {
        onChange(_objectSpread(_objectSpread({}, value), {}, {
          points: points,
          sampleAnswers: sampleAnswers
        }));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeContent", function (index, content, type) {
      // type could be 'points' or 'sampleAnswers'
      log("changeModel[".concat(type, "]:"), index, content);

      if (type !== 'points' && type !== 'sampleAnswers') {
        return;
      }

      var _this$props3 = _this.props,
          value = _this$props3.value,
          onChange = _this$props3.onChange;
      var items = value[type] && Array.from(value[type]);
      items.splice(index, 1, content);
      log("changeModel[".concat(type, "]:"), items);
      onChange(_objectSpread(_objectSpread({}, value), {}, (0, _defineProperty2["default"])({}, type, items)));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "excludeZeros", function () {
      var _this$props4 = _this.props,
          value = _this$props4.value,
          onChange = _this$props4.onChange;
      onChange(_objectSpread(_objectSpread({}, value), {}, {
        excludeZero: !value.excludeZero
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "shouldRenderPoint", function (index, value) {
      if (!value.excludeZero) {
        return true;
      } else {
        if (index < value.points.length - 1) {
          return true;
        } else if (index === value.points.length - 1) {
          return false;
        }

        return true;
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onPointMenuChange", function (index, clickedItem) {
      if (clickedItem === 'sample') {
        var value = _this.props.value;
        var sampleAnswers = Array.from(value.sampleAnswers || []);

        if (checkSampleAnswer(sampleAnswers[index])) {
          // an empty string will display an empty Sample Answer input field
          _this.changeContent(index, '', 'sampleAnswers');
        } else {
          // when the content is null or 'null', the Sample Answer input field will not be displayed
          _this.changeContent(index, null, 'sampleAnswers');
        }
      }
    });
    return _this;
  }

  (0, _createClass2["default"])(RawAuthoring, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props5 = this.props,
          classes = _this$props5.classes,
          className = _this$props5.className,
          value = _this$props5.value,
          _this$props5$mathMlOp = _this$props5.mathMlOptions,
          mathMlOptions = _this$props5$mathMlOp === void 0 ? {} : _this$props5$mathMlOp;

      var _ref = value || {},
          _ref$excludeZeroEnabl = _ref.excludeZeroEnabled,
          excludeZeroEnabled = _ref$excludeZeroEnabl === void 0 ? true : _ref$excludeZeroEnabl,
          _ref$maxPointsEnabled = _ref.maxPointsEnabled,
          maxPointsEnabled = _ref$maxPointsEnabled === void 0 ? true : _ref$maxPointsEnabled;

      if (value && Number.isFinite(value.maxPoints)) {
        // eslint-disable-next-line no-console
        console.warn('maxPoints is deprecated - remove from model');
      }

      return /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames["default"])(classes["class"], className)
      }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
        variant: "h5",
        className: classes.rubricTitle
      }, "Rubric"), /*#__PURE__*/_react["default"].createElement(_FormGroup["default"], {
        row: true
      }, maxPointsEnabled && /*#__PURE__*/_react["default"].createElement(MaxPoints, {
        max: 10,
        value: value.points.length - 1,
        onChange: this.changeMaxPoints
      }), excludeZeroEnabled && /*#__PURE__*/_react["default"].createElement(_FormControlLabel["default"], {
        label: "Exclude zeros",
        control: /*#__PURE__*/_react["default"].createElement(_Checkbox["default"], {
          checked: value.excludeZero,
          onChange: this.excludeZeros
        })
      })), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.container
      }, /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.DragDropContext, {
        onDragEnd: this.dragEnd
      }, /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Droppable, {
        droppableId: "droppable"
      }, function (provided) {
        return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({}, provided.droppableProps, {
          ref: provided.innerRef
        }), value.points.map(function (p, index) {
          return _this2.shouldRenderPoint(index, value) && /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Draggable, {
            key: "".concat(p.points, "-").concat(index),
            index: index,
            draggableId: index.toString()
          }, function (provided) {
            return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
              className: classes.configHolder,
              ref: provided.innerRef
            }, provided.draggableProps, provided.dragHandleProps), /*#__PURE__*/_react["default"].createElement(PointConfig, {
              points: value.points.length - 1 - index,
              content: p,
              sampleAnswer: value.sampleAnswers && value.sampleAnswers[index],
              onChange: function onChange(content) {
                return _this2.changeContent(index, content, 'points');
              },
              onSampleChange: function onSampleChange(content) {
                return _this2.changeContent(index, content, 'sampleAnswers');
              },
              onMenuChange: function onMenuChange(clickedItem) {
                return _this2.onPointMenuChange(index, clickedItem);
              },
              mathMlOptions: mathMlOptions
            }));
          });
        }), provided.placeholder);
      }))));
    }
  }]);
  return RawAuthoring;
}(_react["default"].Component);

exports.RawAuthoring = RawAuthoring;
(0, _defineProperty2["default"])(RawAuthoring, "propTypes", {
  classes: _propTypes["default"].object.isRequired,
  className: _propTypes["default"].string,
  value: RubricType,
  onChange: _propTypes["default"].func
});
(0, _defineProperty2["default"])(RawAuthoring, "defaultProps", {});

var styles = function styles(theme) {
  return {
    container: {
      backgroundColor: _grey["default"][200],
      borderWidth: 1,
      borderStyle: 'solid',
      borderColor: _grey["default"][300],
      padding: theme.spacing.unit * 2,
      margin: theme.spacing.unit
    },
    configHolder: {
      paddingTop: theme.spacing.unit,
      paddingBottom: theme.spacing.unit
    },
    rubricTitle: {
      paddingLeft: theme.spacing.unit,
      margin: theme.spacing.unit
    }
  };
};

var StyledRawAuthoring = (0, _styles.withStyles)(styles)(RawAuthoring);

var Reverse = function Reverse(props) {
  var points = Array.from(props.value.points || []).reverse();
  var sampleAnswers = Array.from(props.value.sampleAnswers || []).reverse();

  if (points.length > sampleAnswers.length) {
    sampleAnswers = (0, _times["default"])(points.length - sampleAnswers.length).map(function () {
      return null;
    }).concat(sampleAnswers);
  }

  var value = _objectSpread(_objectSpread({}, props.value), {}, {
    points: points,
    sampleAnswers: sampleAnswers
  });

  var onChange = function onChange(value) {
    props.onChange(_objectSpread(_objectSpread({}, value), {}, {
      points: Array.from(value.points || []).reverse(),
      sampleAnswers: Array.from(value.sampleAnswers || []).reverse()
    }));
  };

  return /*#__PURE__*/_react["default"].createElement(StyledRawAuthoring, {
    value: value,
    onChange: onChange
  });
};

Reverse.propTypes = {
  value: RubricType,
  getIndex: _propTypes["default"].func,
  onChange: _propTypes["default"].func
};
var _default = Reverse;
exports["default"] = _default;
//# sourceMappingURL=authoring.js.map