"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.AlternateResponses = 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 _isEqual = _interopRequireDefault(require("lodash/isEqual"));

var _map = _interopRequireDefault(require("lodash/map"));

var _reduce = _interopRequireDefault(require("lodash/reduce"));

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var _alternateSection = _interopRequireDefault(require("./alternateSection"));

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 AlternateResponses = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(AlternateResponses, _React$Component);

  var _super = _createSuper(AlternateResponses);

  function AlternateResponses() {
    var _this;

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

    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", {
      maxLengthPerChoice: (0, _cloneDeep["default"])(_this.props.model.maxLengthPerChoice)
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateChoicesIfNeeded", function (props) {
      if (!_this.state.choices || !(0, _isEqual["default"])(_this.state.choices, props.model.choices) || !(0, _isEqual["default"])(props.model.choices, _this.props.model.choices) || _this.state.values && Object.keys(_this.state.values).length !== Object.keys(_this.props.model.choices).length || props.maxLengthPerChoiceEnabled !== _this.props.maxLengthPerChoiceEnabled) {
        var _props$model = props.model,
            choices = _props$model.choices,
            maxLengthPerChoice = _props$model.maxLengthPerChoice;
        var selectedValues = (0, _reduce["default"])(choices, function (obj, c, key) {
          // if maxLengthPerChoiceEnabled is true, we display all the choices
          if (c && (props.maxLengthPerChoiceEnabled || c.length > 1)) {
            obj[key] = c[0];
          }

          return obj;
        }, {});

        _this.setState({
          choices: props.model.choices,
          values: selectedValues,
          maxLengthPerChoice: (0, _cloneDeep["default"])(maxLengthPerChoice)
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getRemainingChoices", function (valueKey) {
      var choices = _this.state.choices;
      return (0, _reduce["default"])(choices, function (arr, c, key) {
        if (c && c.length === 1 && !valueKey) {
          arr.push({
            label: c[0].label,
            value: key
          });
        }

        return arr;
      }, []);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChoiceChanged", function (choice, key) {
      var onChange = _this.props.onChange;
      var choices = _this.state.choices;
      var sectionChoices = choices[key] || [];
      var isNew = !sectionChoices.find(function (c) {
        return c.value === choice.value;
      });
      var newChoices = sectionChoices.reduce(function (arr, c) {
        var newVal = c.value === choice.value ? choice : c;
        arr.push(newVal);
        return arr;
      }, []);

      if (isNew) {
        newChoices.push(choice);
      }

      onChange(_objectSpread(_objectSpread({}, choices), {}, (0, _defineProperty2["default"])({}, key, newChoices)));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChoiceRemoved", function (value, section) {
      var onChange = _this.props.onChange;
      var choices = _this.state.choices;
      var sectionChoices = choices[section] || [];
      var newChoices = sectionChoices.reduce(function (arr, c) {
        if (c.value === value) {
          return arr;
        }

        arr.push(c);
        return arr;
      }, []);
      onChange(_objectSpread(_objectSpread({}, choices), {}, (0, _defineProperty2["default"])({}, section, newChoices)));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSectionSelect", function (choice, key) {
      var onChange = _this.props.onChange;
      var _this$state = _this.state,
          choices = _this$state.choices,
          values = _this$state.values;

      if (choices[key] && choices[key].length > 1) {
        if (!choice) {
          onChange(_objectSpread(_objectSpread({}, choices), {}, (0, _defineProperty2["default"])({}, key, [choices[key][0]])));
        }
      } else {
        _this.setState({
          choices: _objectSpread(_objectSpread({}, choices), {}, (0, _defineProperty2["default"])({}, key, [].concat((0, _toConsumableArray2["default"])(choices[key]), [{
            label: '',
            value: '1'
          }]))),
          values: _objectSpread(_objectSpread({}, values), {}, (0, _defineProperty2["default"])({}, key, choices[key][0]))
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onLengthChanged", function (value, key) {
      var _this$props = _this.props,
          model = _this$props.model,
          onLengthChange = _this$props.onLengthChange;
      var maxLengthPerChoice = model.maxLengthPerChoice;
      maxLengthPerChoice[key] = value;
      onLengthChange(maxLengthPerChoice);
    });
    return _this;
  }

  (0, _createClass2["default"])(AlternateResponses, [{
    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 _this2 = this;

      var choices = this.state.choices;
      var _this$props2 = this.props,
          _this$props2$model = _this$props2.model,
          maxLengthPerChoice = _this$props2$model.maxLengthPerChoice,
          maxLengthPerChoiceEnabled = _this$props2$model.maxLengthPerChoiceEnabled,
          spellCheck = _this$props2.spellCheck,
          choicesErrors = _this$props2.choicesErrors;
      return /*#__PURE__*/_react["default"].createElement("div", null, (0, _map["default"])(choices, function (c, key) {
        // if maxLengthPerChoiceEnabled is true, we display all the choices
        if (c && (maxLengthPerChoiceEnabled || c.length > 1)) {
          var selected = _this2.state.values[key];
          return /*#__PURE__*/_react["default"].createElement(_alternateSection["default"], {
            key: key,
            value: selected && selected.value,
            errors: choicesErrors && choicesErrors[key],
            onSelect: function onSelect(choice) {
              return _this2.onSectionSelect(choice, key);
            },
            choiceChanged: function choiceChanged(choice) {
              return _this2.onChoiceChanged(choice, key);
            },
            choiceRemoved: function choiceRemoved(value) {
              return _this2.onChoiceRemoved(value, key);
            },
            lengthChanged: function lengthChanged(value) {
              return _this2.onLengthChanged(value, key);
            },
            selectChoices: [selected],
            choices: c,
            maxLength: maxLengthPerChoice[key],
            showMaxLength: maxLengthPerChoiceEnabled,
            spellCheck: spellCheck
          });
        }
      }), choices && Object.keys(this.state.values).length !== Object.keys(choices).length && /*#__PURE__*/_react["default"].createElement(_alternateSection["default"], {
        value: "",
        onSelect: function onSelect(choice) {
          return _this2.onSectionSelect(choice, choice.value);
        },
        choiceChanged: function choiceChanged(choice) {
          return _this2.onChoiceChanged(choice);
        },
        choiceRemoved: function choiceRemoved(value) {
          return _this2.onChoiceRemoved(value);
        },
        selectChoices: this.getRemainingChoices(),
        spellCheck: spellCheck
      }));
    }
  }]);
  return AlternateResponses;
}(_react["default"].Component);

exports.AlternateResponses = AlternateResponses;
(0, _defineProperty2["default"])(AlternateResponses, "propTypes", {
  choicesErrors: _propTypes["default"].object,
  model: _propTypes["default"].object.isRequired,
  onChange: _propTypes["default"].func.isRequired,
  onLengthChange: _propTypes["default"].func.isRequired,
  maxLengthPerChoiceEnabled: _propTypes["default"].bool.isRequired,
  spellCheck: _propTypes["default"].bool
});
var _default = AlternateResponses;
exports["default"] = _default;
//# sourceMappingURL=alternateResponses.js.map