"use strict";

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

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

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

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 React = _interopRequireWildcard(require("react"));

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

var _configUi = require("@pie-lib/pie-toolbox/config-ui");

var _mathToolbar = require("@pie-lib/pie-toolbox/math-toolbar");

var _Card = _interopRequireDefault(require("@material-ui/core/Card"));

var _CardContent = _interopRequireDefault(require("@material-ui/core/CardContent"));

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

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

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

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

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

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

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

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

var _renderUi = require("@pie-lib/pie-toolbox/render-ui");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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

// TODO once we support individual response correctness, we need to remove this constant
var INDIVIDUAL_RESPONSE_CORRECTNESS_SUPPORTED = false;

var styles = function styles(theme) {
  return {
    responseContainer: {
      marginBottom: theme.spacing.unit * 2.5,
      width: '100%',
      minWidth: '548px',
      border: "1px solid ".concat(theme.palette.grey[700]),
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'space-between'
    },
    cardContent: {
      paddingBottom: "".concat(theme.spacing.unit * 2, "px !important")
    },
    title: {
      fontWeight: 700,
      fontSize: '1.2rem',
      flex: 3
    },
    selectContainer: {
      flex: 2
    },
    inputContainer: {
      marginBottom: theme.spacing.unit * 2
    },
    titleBar: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between'
    },
    responseEditor: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      width: '100%',
      minWidth: '500px',
      maxWidth: '900px',
      height: 'auto',
      minHeight: '40px'
    },
    mathToolbar: {
      width: '100%'
    },
    alternateButton: {
      border: "1px solid ".concat(theme.palette.grey['A100'])
    },
    removeAlternateButton: {
      marginLeft: theme.spacing.unit * 2,
      border: "1px solid ".concat(theme.palette.grey['A100']),
      color: 'gray',
      fontSize: '0.8rem'
    },
    errorText: {
      fontSize: theme.typography.fontSize - 2,
      color: theme.palette.error.main,
      paddingTop: theme.spacing.unit
    },
    customColor: {
      color: "".concat(_renderUi.color.tertiary(), " !important")
    }
  };
};

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

  var _super = _createSuper(Response);

  function Response(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Response);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChange", function (name) {
      return function (evt) {
        var _this$props = _this.props,
            response = _this$props.response,
            onResponseChange = _this$props.onResponseChange,
            index = _this$props.index;

        var newResponse = _objectSpread({}, response);

        newResponse[name] = evt.target.value;
        onResponseChange(newResponse, index);
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onConfigChanged", function (name) {
      return function (evt) {
        var _this$props2 = _this.props,
            response = _this$props2.response,
            onResponseChange = _this$props2.onResponseChange,
            index = _this$props2.index;

        var newResponse = _objectSpread({}, response);

        newResponse[name] = evt.target.checked;
        onResponseChange(newResponse, index);
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onLiteralOptionsChange", function (name) {
      return function () {
        var _this$props3 = _this.props,
            response = _this$props3.response,
            onResponseChange = _this$props3.onResponseChange,
            index = _this$props3.index;

        var newResponse = _objectSpread({}, response);

        newResponse[name] = !response[name];
        onResponseChange(newResponse, index);
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onAnswerChange", function (answer) {
      var _this$props4 = _this.props,
          response = _this$props4.response,
          onResponseChange = _this$props4.onResponseChange,
          index = _this$props4.index;

      var newResponse = _objectSpread({}, response);

      newResponse.answer = answer;
      onResponseChange(newResponse, index);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onAlternateAnswerChange", function (alternateId) {
      return function (answer) {
        var _this$props5 = _this.props,
            response = _this$props5.response,
            onResponseChange = _this$props5.onResponseChange,
            index = _this$props5.index;

        var newResponse = _objectSpread({}, response);

        newResponse.alternates[alternateId] = answer;
        onResponseChange(newResponse, index);
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onAddAlternate", function () {
      var _this$props6 = _this.props,
          response = _this$props6.response,
          onResponseChange = _this$props6.onResponseChange,
          index = _this$props6.index;
      var alternateIdCounter = _this.state.alternateIdCounter;

      var newResponse = _objectSpread({}, response);

      if (!newResponse.alternates) {
        newResponse.alternates = {};
      }

      newResponse.alternates[alternateIdCounter] = '';
      onResponseChange(newResponse, index);

      _this.setState({
        alternateIdCounter: alternateIdCounter + 1
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onRemoveAlternate", function (alternateId) {
      return function () {
        var _this$props7 = _this.props,
            response = _this$props7.response,
            onResponseChange = _this$props7.onResponseChange,
            index = _this$props7.index;

        var newResponse = _objectSpread({}, response);

        delete newResponse.alternates[alternateId];
        onResponseChange(newResponse, index);

        _this.setState(function (state) {
          return {
            showKeypad: _objectSpread(_objectSpread({}, state.showKeypad), {}, {
              openCount: !state.showKeypad[alternateId] ? state.showKeypad.openCount : state.showKeypad.openCount - 1
            })
          };
        });
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDone", function () {
      _this.setState(function (state) {
        return {
          showKeypad: _objectSpread(_objectSpread({}, state.showKeypad), {}, {
            openCount: state.showKeypad.openCount - 1,
            main: false
          })
        };
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onFocus", function () {
      _this.setState(function (state) {
        return {
          showKeypad: _objectSpread(_objectSpread({}, state.showKeypad), {}, {
            openCount: !state.showKeypad.main ? state.showKeypad.openCount + 1 : state.showKeypad.openCount,
            main: true
          })
        };
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onAlternateFocus", function (alternateId) {
      return function () {
        _this.setState(function (state) {
          return {
            showKeypad: _objectSpread(_objectSpread({}, state.showKeypad), {}, (0, _defineProperty2["default"])({
              openCount: !state.showKeypad[alternateId] ? state.showKeypad.openCount + 1 : state.showKeypad.openCount
            }, alternateId, true))
          };
        });
      };
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onAlternateDone", function (alternateId) {
      return function () {
        _this.setState(function (state) {
          return {
            showKeypad: _objectSpread(_objectSpread({}, state.showKeypad), {}, (0, _defineProperty2["default"])({
              openCount: state.showKeypad.openCount - 1
            }, alternateId, false))
          };
        });
      };
    });

    var _ref = props || {},
        _ref$response = _ref.response;

    _ref$response = _ref$response === void 0 ? {} : _ref$response;
    var alternates = _ref$response.alternates;
    var alternatesLength = Object.keys(alternates || {}).length;
    _this.state = {
      alternateIdCounter: alternatesLength + 1,
      showKeypad: {
        openCount: 0,
        main: false
      }
    };
    return _this;
  }

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

      var _this$props8 = this.props,
          classes = _this$props8.classes,
          mode = _this$props8.mode,
          defaultResponse = _this$props8.defaultResponse,
          index = _this$props8.index,
          response = _this$props8.response,
          cAllowTrailingZeros = _this$props8.cAllowTrailingZeros,
          cIgnoreOrder = _this$props8.cIgnoreOrder,
          error = _this$props8.error;
      var showKeypad = this.state.showKeypad;
      var validation = response.validation,
          answer = response.answer,
          alternates = response.alternates,
          ignoreOrder = response.ignoreOrder,
          allowTrailingZeros = response.allowTrailingZeros;
      var hasAlternates = Object.keys(alternates || {}).length > 0;
      var classNames = {
        editor: classes.responseEditor,
        mathToolbar: classes.mathToolbar
      };
      var styles = {
        minHeight: "".concat(showKeypad.openCount > 0 ? 430 : 230, "px")
      };
      return /*#__PURE__*/React.createElement(_Card["default"], {
        className: classes.responseContainer,
        style: styles
      }, /*#__PURE__*/React.createElement(_CardContent["default"], {
        className: classes.cardContent
      }, /*#__PURE__*/React.createElement("div", {
        className: classes.titleBar
      }, /*#__PURE__*/React.createElement(_Typography["default"], {
        className: classes.title,
        component: "div"
      }, "Response ", INDIVIDUAL_RESPONSE_CORRECTNESS_SUPPORTED ? defaultResponse ? '' : index + 1 : ''), /*#__PURE__*/React.createElement(_configUi.InputContainer, {
        label: "Validation",
        className: classes.selectContainer
      }, /*#__PURE__*/React.createElement(_Select["default"], {
        className: classes.select,
        onChange: this.onChange('validation'),
        value: validation || 'literal'
      }, /*#__PURE__*/React.createElement(_MenuItem["default"], {
        value: "literal"
      }, "Literal Validation"), /*#__PURE__*/React.createElement(_MenuItem["default"], {
        value: "symbolic"
      }, "Symbolic Validation")))), validation === 'literal' && /*#__PURE__*/React.createElement("div", {
        className: classes.flexContainer
      }, cAllowTrailingZeros.enabled && /*#__PURE__*/React.createElement(_FormControlLabel["default"], {
        label: cAllowTrailingZeros.label,
        control: /*#__PURE__*/React.createElement(_Checkbox["default"], {
          className: classes.customColor,
          checked: allowTrailingZeros,
          onChange: this.onLiteralOptionsChange('allowTrailingZeros')
        })
      }), cIgnoreOrder.enabled && /*#__PURE__*/React.createElement(_FormControlLabel["default"], {
        label: cIgnoreOrder.label,
        control: /*#__PURE__*/React.createElement(_Checkbox["default"], {
          className: classes.customColor,
          checked: ignoreOrder,
          onChange: this.onLiteralOptionsChange('ignoreOrder')
        })
      })), /*#__PURE__*/React.createElement("div", {
        className: classes.inputContainer
      }, /*#__PURE__*/React.createElement(_InputLabel["default"], null, "Correct Answer"), /*#__PURE__*/React.createElement(_mathToolbar.MathToolbar, {
        keypadMode: mode,
        classNames: classNames,
        controlledKeypad: true,
        showKeypad: showKeypad.main,
        latex: answer || '',
        onChange: this.onAnswerChange,
        onFocus: this.onFocus,
        onDone: this.onDone,
        error: error && error.answer
      }), error && error.answer ? /*#__PURE__*/React.createElement("div", {
        className: classes.errorText
      }, error.answer) : null), hasAlternates && Object.keys(alternates).map(function (alternateId, altIdx) {
        return /*#__PURE__*/React.createElement("div", {
          className: classes.inputContainer,
          key: alternateId
        }, /*#__PURE__*/React.createElement("div", {
          className: classes.alternateBar
        }, /*#__PURE__*/React.createElement(_InputLabel["default"], null, "Alternate", Object.keys(alternates).length > 1 ? " ".concat(altIdx + 1) : ''), /*#__PURE__*/React.createElement(_Button["default"], {
          className: classes.removeAlternateButton,
          type: "secondary",
          onClick: _this2.onRemoveAlternate(alternateId)
        }, "Remove")), /*#__PURE__*/React.createElement(_mathToolbar.MathToolbar, {
          classNames: classNames,
          controlledKeypad: true,
          keypadMode: mode,
          showKeypad: showKeypad[alternateId] || false,
          latex: alternates[alternateId] || '',
          onChange: _this2.onAlternateAnswerChange(alternateId),
          onFocus: _this2.onAlternateFocus(alternateId),
          onDone: _this2.onAlternateDone(alternateId),
          error: error && error[alternateId]
        }), error && error[alternateId] ? /*#__PURE__*/React.createElement("div", {
          className: classes.errorText
        }, error[alternateId]) : null);
      }), /*#__PURE__*/React.createElement(_Button["default"], {
        className: classes.alternateButton,
        type: "primary",
        onClick: this.onAddAlternate
      }, "ADD ALTERNATE")));
    }
  }]);
  return Response;
}(React.Component);

(0, _defineProperty2["default"])(Response, "propTypes", {
  classes: _propTypes["default"].object.isRequired,
  defaultResponse: _propTypes["default"].bool,
  error: _propTypes["default"].object,
  mode: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number]),
  index: _propTypes["default"].number,
  onResponseChange: _propTypes["default"].func.isRequired,
  response: _propTypes["default"].object.isRequired,
  cIgnoreOrder: _propTypes["default"].object.isRequired,
  cAllowTrailingZeros: _propTypes["default"].object.isRequired
});
(0, _defineProperty2["default"])(Response, "defaultProps", {
  defaultResponse: false,
  mode: 'miscellaneous'
});

var _default = (0, _styles.withStyles)(styles)(Response);

exports["default"] = _default;
//# sourceMappingURL=response.js.map