"use strict";

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

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

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

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

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

var _debounce = _interopRequireDefault(require("lodash/debounce"));

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

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

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

var _Delete = _interopRequireDefault(require("@material-ui/icons/Delete"));

var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton"));

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

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

var _TextField = _interopRequireDefault(require("@material-ui/core/TextField"));

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

var _max = _interopRequireDefault(require("lodash/max"));

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

var _markupUtils = require("./markupUtils");

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 styles = function styles(theme) {
  return {
    design: {
      marginBottom: theme.spacing.unit / 2
    },
    altChoices: {
      alignItems: 'flex-start',
      flexDirection: 'column',
      display: 'flex',
      paddingTop: theme.spacing.unit * 2.5,
      '& > *': {
        marginBottom: theme.spacing.unit * 2.5,
        width: '100%'
      }
    },
    choice: {
      flex: '1',
      marginRight: theme.spacing.unit * 2.5
    },
    deleteBtn: {
      fill: theme.palette.grey[600]
    },
    selectContainer: {
      alignItems: 'flex-end',
      display: 'flex',
      justifyContent: 'space-between',
      width: '100%'
    },
    rightContainer: {
      alignItems: 'center',
      display: 'flex'
    },
    lengthField: {
      width: '230px',
      marginRight: theme.spacing.unit * 2.5
    },
    errorText: {
      fontSize: theme.typography.fontSize - 2,
      color: theme.palette.error.main,
      paddingTop: theme.spacing.unit / 2
    },
    inputError: {
      border: "2px solid ".concat(theme.palette.error.main),
      borderRadius: '6px'
    }
  };
};

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

  var _super = _createSuper(Choice);

  function Choice() {
    var _this;

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

    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), "state", {
      value: _this.props.markup
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateText", (0, _debounce["default"])(_this.props.onChange, 300));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChange", function (e) {
      var value = e.target.value;

      _this.setState({
        value: value
      });

      _this.updateText(value);
    });
    return _this;
  }

  (0, _createClass2["default"])(Choice, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if (nextProps.markup) {
        this.setState({
          value: nextProps.markup
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var value = this.state.value;
      var _this$props = this.props,
          classes = _this$props.classes,
          onDelete = _this$props.onDelete,
          spellCheck = _this$props.spellCheck,
          error = _this$props.error,
          showMaxLength = _this$props.showMaxLength;
      var inputProps = showMaxLength ? {} : {
        maxLength: 25
      };
      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          alignItems: 'center',
          display: 'flex',
          justifyContent: 'space-between'
        }
      }, /*#__PURE__*/_react["default"].createElement(_OutlinedInput["default"], {
        className: (0, _classnames["default"])(classes.choice, error && classes.inputError),
        value: value,
        onChange: this.onChange,
        labelWidth: 0,
        disableUnderline: true,
        spellCheck: spellCheck,
        inputProps: inputProps
      }), /*#__PURE__*/_react["default"].createElement(_IconButton["default"], {
        "aria-label": "delete",
        className: classes.deleteBtn,
        onClick: onDelete
      }, /*#__PURE__*/_react["default"].createElement(_Delete["default"], null))), error && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, error));
    }
  }]);
  return Choice;
}(_react["default"].Component);

exports.Choice = Choice;
(0, _defineProperty2["default"])(Choice, "propTypes", {
  classes: _propTypes["default"].object,
  error: _propTypes["default"].string,
  markup: _propTypes["default"].string,
  onChange: _propTypes["default"].func.isRequired,
  onDelete: _propTypes["default"].func.isRequired,
  value: _propTypes["default"].string,
  spellCheck: _propTypes["default"].bool,
  showMaxLength: _propTypes["default"].bool
});

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

  var _super2 = _createSuper(AlternateSection);

  function AlternateSection() {
    var _this2;

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

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

    _this2 = _super2.call.apply(_super2, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "state", {});
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "updateChoicesIfNeeded", function (props) {
      if (!_this2.state.choices || !(0, _isEqual["default"])(props.choices, _this2.state.choices) || !(0, _isEqual["default"])(props.choices, _this2.props.choices)) {
        _this2.setState({
          choices: props.choices
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "handleSelect", function (e) {
      var _this2$props = _this2.props,
          onSelect = _this2$props.onSelect,
          selectChoices = _this2$props.selectChoices;
      var value = e.target.value;
      onSelect(selectChoices.find(function (c) {
        return c.value === value;
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "onAddChoice", function () {
      var choices = _this2.state.choices;

      if (choices.length && choices[choices.length - 1].label !== '') {
        var value = (0, _max["default"])(choices.map(function (c) {
          return parseInt(c.value);
        }).filter(function (id) {
          return !isNaN(id);
        })) || 0;

        _this2.setState({
          choices: [].concat((0, _toConsumableArray2["default"])(choices), [{
            value: "".concat(value + 1),
            label: ''
          }])
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "onChoiceChanged", function (choice, value, index) {
      var _this2$props2 = _this2.props,
          choiceChanged = _this2$props2.choiceChanged,
          lengthChanged = _this2$props2.lengthChanged,
          maxLength = _this2$props2.maxLength,
          choices = _this2$props2.choices;
      var labelLengthsArr = choices.map(function (choice) {
        return (choice.label || '').length;
      });
      labelLengthsArr[index] = value.length;
      var newLength = Math.max.apply(Math, (0, _toConsumableArray2["default"])(labelLengthsArr));
      choiceChanged(_objectSpread(_objectSpread({}, choice), {}, {
        label: value
      }));

      if (newLength > maxLength || newLength + 10 <= maxLength) {
        lengthChanged((0, _markupUtils.getAdjustedLength)(newLength));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "onRemoveChoice", function (choice) {
      var choiceRemoved = _this2.props.choiceRemoved;
      choiceRemoved(choice.value);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "getChoicesMaxLength", function () {
      var choices = _this2.state.choices;

      if (!choices) {
        return 1;
      }

      var labelLengthsArr = choices.map(function (choice) {
        return (choice.label || '').length;
      });
      return Math.max.apply(Math, (0, _toConsumableArray2["default"])(labelLengthsArr));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "changeLength", function (event) {
      var lengthChanged = _this2.props.lengthChanged;
      var numberValue = parseInt(event.target.value, 10);

      var minLength = _this2.getChoicesMaxLength();

      if (numberValue && numberValue >= minLength && numberValue <= minLength + 10) {
        lengthChanged(numberValue);
      }
    });
    return _this2;
  }

  (0, _createClass2["default"])(AlternateSection, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      this.updateChoicesIfNeeded(nextProps);
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.updateChoicesIfNeeded(this.props);
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props2 = this.props,
          classes = _this$props2.classes,
          selectChoices = _this$props2.selectChoices,
          maxLength = _this$props2.maxLength,
          showMaxLength = _this$props2.showMaxLength,
          value = _this$props2.value,
          spellCheck = _this$props2.spellCheck,
          errors = _this$props2.errors;
      var choices = this.state.choices;
      var minLength = this.getChoicesMaxLength();
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.design
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.selectContainer
      }, /*#__PURE__*/_react["default"].createElement(_Select["default"], {
        className: classes.select,
        displayEmpty: true,
        onChange: this.handleSelect,
        value: value || '',
        readOnly: showMaxLength
      }, /*#__PURE__*/_react["default"].createElement(_MenuItem["default"], {
        value: ""
      }, /*#__PURE__*/_react["default"].createElement("em", null, value ? 'Remove selection' : 'Select a response')), selectChoices.map(function (c, index) {
        return /*#__PURE__*/_react["default"].createElement(_MenuItem["default"], {
          key: index,
          value: c === null || c === void 0 ? void 0 : c.value
        }, c === null || c === void 0 ? void 0 : c.label);
      })), choices && choices.length > 0 && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.rightContainer
      }, maxLength && showMaxLength && /*#__PURE__*/_react["default"].createElement(_TextField["default"], {
        className: classes.lengthField,
        label: "Maximum length (characters)",
        type: "number",
        inputProps: {
          min: minLength,
          max: minLength + 10
        },
        value: maxLength,
        onChange: this.changeLength
      }), /*#__PURE__*/_react["default"].createElement(_Button["default"], {
        className: classes.addButton,
        variant: "contained",
        color: "primary",
        onClick: this.onAddChoice
      }, "Add"))), errors && errors[0] && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, errors[0]), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.altChoices
      }, choices && choices.map(function (c, index) {
        return index > 0 && /*#__PURE__*/_react["default"].createElement(Choice, {
          key: index,
          classes: classes,
          markup: c.label,
          onChange: function onChange(val) {
            return _this3.onChoiceChanged(c, val, index);
          },
          onDelete: function onDelete() {
            return _this3.onRemoveChoice(c);
          },
          spellCheck: spellCheck,
          error: errors && errors[index],
          showMaxLength: showMaxLength
        });
      })));
    }
  }]);
  return AlternateSection;
}(_react["default"].Component);

exports.AlternateSection = AlternateSection;
(0, _defineProperty2["default"])(AlternateSection, "propTypes", {
  choices: _propTypes["default"].array,
  selectChoices: _propTypes["default"].array.isRequired,
  classes: _propTypes["default"].object.isRequired,
  errors: _propTypes["default"].object,
  onSelect: _propTypes["default"].func.isRequired,
  choiceChanged: _propTypes["default"].func.isRequired,
  lengthChanged: _propTypes["default"].func,
  choiceRemoved: _propTypes["default"].func.isRequired,
  value: _propTypes["default"].string,
  maxLength: _propTypes["default"].number,
  showMaxLength: _propTypes["default"].bool,
  spellCheck: _propTypes["default"].bool
});
var Styled = (0, _styles.withStyles)(styles)(AlternateSection);
var _default = Styled;
exports["default"] = _default;
//# sourceMappingURL=alternateSection.js.map