"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ComponentContainer = require("../../../Framework/ComponentContainer");
var _BulkNames = _interopRequireDefault(require("../Components/BulkNames"));
var _find = _interopRequireDefault(require("lodash/find"));
var _sumBy = _interopRequireDefault(require("lodash/sumBy"));
var _flatten = _interopRequireDefault(require("lodash/flatten"));
var _get = _interopRequireDefault(require("lodash/get"));
var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));
var _excluded = ["BulkNamesComponent", "activeSizeVariant"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var BulkNamesContainer = /*#__PURE__*/function (_React$Component) {
  _inherits(BulkNamesContainer, _React$Component);
  var _super = _createSuper(BulkNamesContainer);
  function BulkNamesContainer() {
    var _this;
    _classCallCheck(this, BulkNamesContainer);
    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));
    _defineProperty(_assertThisInitialized(_this), "initialState", {
      textInputs: [{
        text: '',
        amount: 1
      }]
    });
    _defineProperty(_assertThisInitialized(_this), "state", _this.initialState);
    _defineProperty(_assertThisInitialized(_this), "totalAmount", function () {
      var textInputs = _this.state.textInputs;
      var filledBulkNameInputs = [];
      var _iterator = _createForOfIteratorHelper(textInputs),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var input = _step.value;
          if (input.text !== '') {
            if (input.amount === 0) {
              input.amount = 1;
            }
            filledBulkNameInputs.push(input);
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return (0, _sumBy["default"])(filledBulkNameInputs, 'amount');
    });
    _defineProperty(_assertThisInitialized(_this), "saveBulkNamesConfiguration", function () {
      var _this$props = _this.props,
        selectedVariant = _this$props.selectedVariant,
        activeSizeVariant = _this$props.activeSizeVariant,
        handleChange = _this$props.handleChange,
        handleSave = _this$props.handleSave,
        onClose = _this$props.onClose;
      var textInputs = _this.state.textInputs;
      var summedAmount = _this.totalAmount();
      handleChange(summedAmount);
      var reformattedTextInputs = (0, _flatten["default"])(textInputs.map(function (input) {
        var inputs = [];
        if (input.text !== '') {
          for (var i = 1; i <= input.amount; i++) {
            inputs.push(input.text);
          }
        }
        return inputs;
      }));
      if (selectedVariant.sizes.length > 0) {
        var sizeVariant = (0, _find["default"])(selectedVariant.sizes, {
          identifier: activeSizeVariant.identifier
        });
        handleSave(sizeVariant.identifier, reformattedTextInputs);
      } else {
        handleSave(selectedVariant.identifier, reformattedTextInputs);
      }
      onClose();
    });
    _defineProperty(_assertThisInitialized(_this), "handleText", function (text, i) {
      return function (e) {
        var textInputs = _toConsumableArray(_this.state.textInputs);
        if (text === 'text') {
          textInputs[i].text = e.target.value;
        } else {
          textInputs[i].amount = e;
        }
        _this.setState({
          textInputs: textInputs
        });
      };
    });
    _defineProperty(_assertThisInitialized(_this), "addTextField", function (e) {
      e.preventDefault();
      var textInputs = _this.state.textInputs.concat({
        text: '',
        amount: 1
      });
      _this.setState({
        textInputs: textInputs
      });
    });
    _defineProperty(_assertThisInitialized(_this), "handleDelete", function (i) {
      return function (e) {
        e.preventDefault();
        var textInputs = [].concat(_toConsumableArray(_this.state.textInputs.slice(0, i)), _toConsumableArray(_this.state.textInputs.slice(i + 1)));
        _this.setState({
          textInputs: textInputs
        });
      };
    });
    return _this;
  }
  _createClass(BulkNamesContainer, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props2 = this.props,
        selectedVariant = _this$props2.selectedVariant,
        activeSizeVariant = _this$props2.activeSizeVariant;
      if (selectedVariant.sizes.length > 0) {
        var sizeVariant = (0, _find["default"])(selectedVariant.sizes, {
          identifier: activeSizeVariant.identifier
        });
        var bulkNamesSizes = sizeVariant.bulkNames;
        var bulkNamesInputs = Object.values(bulkNamesSizes.reduce(function (indexedNames, text) {
          var amount = (0, _get["default"])(indexedNames, "".concat(text, ".amount"), 0) + 1;
          indexedNames = _objectSpread(_objectSpread({}, indexedNames), {}, _defineProperty({}, text, {
            text: text,
            amount: amount
          }));
          return indexedNames;
        }, {}));
        if (bulkNamesSizes.length > 0) {
          this.setState({
            textInputs: bulkNamesInputs
          });
        }
      } else {
        var bulkNames = selectedVariant.bulkNames;
        var _bulkNamesInputs = Object.values(bulkNames.reduce(function (indexedNames, text) {
          var amount = (0, _get["default"])(indexedNames, "".concat(text, ".amount"), 0) + 1;
          indexedNames = _objectSpread(_objectSpread({}, indexedNames), {}, _defineProperty({}, text, {
            text: text,
            amount: amount
          }));
          return indexedNames;
        }, {}));
        if (bulkNames.length > 0) {
          this.setState({
            textInputs: _bulkNamesInputs
          });
        }
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;
      var textInputs = this.state.textInputs;
      var _this$props3 = this.props,
        BulkNamesComponent = _this$props3.BulkNamesComponent,
        activeSizeVariant = _this$props3.activeSizeVariant,
        props = _objectWithoutProperties(_this$props3, _excluded);
      var size = !(0, _isEmpty["default"])(activeSizeVariant) && activeSizeVariant.size.split(' ').pop();
      return /*#__PURE__*/_react["default"].createElement(BulkNamesComponent, _extends({
        handleDelete: this.handleDelete,
        addTextField: this.addTextField,
        textInputs: textInputs,
        handleText: this.handleText,
        saveConfigurationBulkNames: function saveConfigurationBulkNames() {
          return _this2.saveBulkNamesConfiguration();
        },
        totalAmount: this.totalAmount,
        size: size,
        activeSizeVariant: activeSizeVariant
      }, props));
    }
  }]);
  return BulkNamesContainer;
}(_react["default"].Component);
var mapStateToProps = function mapStateToProps() {
  return {
    Component: BulkNamesContainer,
    BulkNamesComponent: _BulkNames["default"]
  };
};
var _default = exports["default"] = (0, _ComponentContainer.containerConnect)(mapStateToProps);