"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.Scale = 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 _styles = require("@material-ui/core/styles");

var _ArrowBackIos = _interopRequireDefault(require("@material-ui/icons/ArrowBackIos"));

var _ArrowForwardIos = _interopRequireDefault(require("@material-ui/icons/ArrowForwardIos"));

var _drag = require("@pie-lib/drag");

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

var _traitsHeader = _interopRequireDefault(require("./traitsHeader"));

var _trait = _interopRequireDefault(require("./trait"));

var _common = require("./common");

var _modals = require("./modals");

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 AdjustedBlockWidth = _common.BlockWidth + 2 * 8; // 8 is padding

var styles = function styles(theme) {
  return {
    scaleWrapper: {
      display: 'flex',
      flexDirection: 'column',
      wordBreak: 'break-word',
      position: 'relative',
      marginBottom: theme.spacing.unit * 2.5
    },
    maxPoints: {
      width: '300px',
      marginTop: theme.spacing.unit * 2,
      marginBottom: theme.spacing.unit * 4
    },
    trait: {
      background: _renderUi.color.secondaryBackground(),
      marginTop: theme.spacing.unit * 2,
      marginBottom: theme.spacing.unit * 2,
      padding: theme.spacing.unit * 2
    }
  };
};

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

  var _super = _createSuper(Scale);

  function Scale() {
    var _this;

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

    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", {
      showDecreaseMaxPointsDialog: false,
      showDeleteScaleDialog: false,
      showDeleteTraitDialog: false,
      currentPosition: 0,
      showRight: null,
      showLeft: null,
      showInfoDialog: false,
      infoDialogText: ''
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "set", function (newState) {
      return _this.setState(newState);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateMaxPointsFieldValue", function (_ref) {
      var target = _ref.target;

      var _ref2 = _this.props || {},
          scale = _ref2.scale,
          scaleIndex = _ref2.scaleIndex,
          onScaleChanged = _ref2.onScaleChanged;

      var maxPoints = scale.maxPoints;
      var numberValue = parseInt(target.value, 10);

      _this.setState({
        currentPosition: 0,
        showLeft: false,
        showRight: _this.secondaryBlockRef && _this.secondaryBlockRef.scrollWidth - _this.secondaryBlockRef.offsetWidth
      });

      if (numberValue < maxPoints) {
        _this.showDecreaseMaxPointsModal({
          newMaxPoints: numberValue
        });
      } else {
        onScaleChanged(scaleIndex, {
          maxPoints: numberValue
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "showDecreaseMaxPointsModal", function (_ref3) {
      var newMaxPoints = _ref3.newMaxPoints;
      return _this.set({
        showDecreaseMaxPointsDialog: true,
        newMaxPoints: newMaxPoints
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hideDecreaseMaxPointsModal", function () {
      return _this.set({
        showDecreaseMaxPointsDialog: false,
        newMaxPoints: undefined
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeMaxPoints", function () {
      var _ref4 = _this.state || {},
          newMaxPoints = _ref4.newMaxPoints;

      var _ref5 = _this.props || {},
          scaleIndex = _ref5.scaleIndex,
          onScaleChanged = _ref5.onScaleChanged;

      if (newMaxPoints) {
        onScaleChanged(scaleIndex, {
          maxPoints: newMaxPoints
        });
      }

      _this.hideDecreaseMaxPointsModal();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "showDeleteScaleModal", function () {
      return _this.set({
        showDeleteScaleDialog: true
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hideDeleteScaleModal", function () {
      return _this.set({
        showDeleteScaleDialog: false
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "deleteScale", function () {
      var _ref6 = _this.props || {},
          scaleIndex = _ref6.scaleIndex,
          onScaleRemoved = _ref6.onScaleRemoved;

      _this.hideDeleteScaleModal();

      onScaleRemoved(scaleIndex);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "showDeleteTraitModal", function (traitToDeleteIndex) {
      return _this.set({
        showDeleteTraitDialog: true,
        traitToDeleteIndex: traitToDeleteIndex
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hideDeleteTraitModal", function () {
      return _this.set({
        showDeleteTraitDialog: false,
        traitToDeleteIndex: undefined
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTraitRemoved", function () {
      var traitToDeleteIndex = _this.state.traitToDeleteIndex;

      var _ref7 = _this.props || {},
          scale = _ref7.scale,
          scaleIndex = _ref7.scaleIndex,
          onScaleChanged = _ref7.onScaleChanged,
          minNoOfTraits = _ref7.minNoOfTraits;

      var _ref8 = scale || {},
          traits = _ref8.traits,
          traitLabel = _ref8.traitLabel;

      if (traitToDeleteIndex < 0 || traitToDeleteIndex >= traits.length) return;

      if (traits.length === minNoOfTraits) {
        _this.set({
          infoDialogText: "There can't be less than ".concat(minNoOfTraits, " ").concat((traitLabel || 'trait').toLowerCase(), "s."),
          showInfoDialog: true
        });

        return false;
      }

      traits = [].concat((0, _toConsumableArray2["default"])(traits.slice(0, traitToDeleteIndex)), (0, _toConsumableArray2["default"])(traits.slice(traitToDeleteIndex + 1)));
      onScaleChanged(scaleIndex, {
        traits: traits
      });

      _this.hideDeleteTraitModal();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTraitAdded", function () {
      var _ref9 = _this.props || {},
          scale = _ref9.scale,
          scaleIndex = _ref9.scaleIndex,
          onScaleChanged = _ref9.onScaleChanged,
          maxNoOfTraits = _ref9.maxNoOfTraits;

      var _ref10 = scale || {},
          traits = _ref10.traits,
          scorePointsLabels = _ref10.scorePointsLabels;

      if (traits.length === maxNoOfTraits) {
        _this.set({
          infoDialogText: "There can't be more than ".concat(maxNoOfTraits, " scales."),
          showInfoDialog: true
        });

        return false;
      }

      traits.push({
        name: '',
        description: '',
        standards: [],
        scorePointsDescriptors: Array.from({
          length: scorePointsLabels.length
        }, function () {
          return '';
        })
      });
      onScaleChanged(scaleIndex, {
        traits: traits
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTraitChanged", function (traitIndex, trait) {
      var _ref11 = _this.props || {},
          scale = _ref11.scale,
          scaleIndex = _ref11.scaleIndex,
          onScaleChanged = _ref11.onScaleChanged;

      var _ref12 = scale || {},
          traits = _ref12.traits;

      if (traitIndex >= 0 && traitIndex < traits.length) {
        traits[traitIndex] = trait;
        onScaleChanged(scaleIndex, {
          traits: traits
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTraitDropped", function (source, newIndex) {
      var _ref13 = _this.props || {},
          scale = _ref13.scale,
          scaleIndex = _ref13.scaleIndex,
          onScaleChanged = _ref13.onScaleChanged;

      var _ref14 = scale || {},
          traits = _ref14.traits;

      var oldIndex = source.index;
      var cup = traits[oldIndex];
      var remainingTraits = traits.filter(function (item, index) {
        return index !== oldIndex;
      });
      var newTraits = [].concat((0, _toConsumableArray2["default"])(remainingTraits.slice(0, newIndex)), [cup], (0, _toConsumableArray2["default"])(remainingTraits.slice(newIndex)));
      onScaleChanged(scaleIndex, {
        traits: newTraits
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "decreasePosition", function () {
      var currentPosition = _this.state.currentPosition;
      var decreasedPosition = currentPosition - (currentPosition === AdjustedBlockWidth / 2 ? AdjustedBlockWidth / 2 : AdjustedBlockWidth);

      _this.setState({
        currentPosition: decreasedPosition,
        showRight: decreasedPosition < _this.secondaryBlockRef.scrollWidth - _this.secondaryBlockRef.offsetWidth,
        showLeft: decreasedPosition > 0
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "increasePosition", function () {
      var currentPosition = _this.state.currentPosition;
      var increasedPosition = currentPosition + (currentPosition === 0 ? AdjustedBlockWidth / 2 : AdjustedBlockWidth);

      _this.setState({
        currentPosition: increasedPosition,
        showRight: increasedPosition < _this.secondaryBlockRef.scrollWidth - _this.secondaryBlockRef.offsetWidth,
        showLeft: increasedPosition > 0
      });
    });
    return _this;
  }

  (0, _createClass2["default"])(Scale, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.state.showRight === null && this.secondaryBlockRef) {
        this.setState({
          showRight: this.secondaryBlockRef.scrollWidth - this.secondaryBlockRef.offsetWidth
        });
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (prevProps.scale.maxPoints !== this.props.scale.maxPoints || prevProps.showDescription !== this.props.showDescription || prevProps.excludeZero !== this.props.excludeZero) {
        this.setState({
          showRight: this.secondaryBlockRef.scrollWidth - this.secondaryBlockRef.offsetWidth
        });
      }
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if (nextProps.excludeZero !== this.props.excludeZero || nextProps.showStandards !== this.props.showStandards || nextProps.showDescription !== this.props.showDescription) {
        this.setState({
          currentPosition: 0,
          showLeft: false,
          showRight: this.secondaryBlockRef && this.secondaryBlockRef.scrollWidth - this.secondaryBlockRef.offsetWidth
        });
      }
    } // Max Points

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _ref15 = this.props || {},
          classes = _ref15.classes,
          errors = _ref15.errors,
          scale = _ref15.scale,
          scaleIndex = _ref15.scaleIndex,
          showStandards = _ref15.showStandards,
          onScaleChanged = _ref15.onScaleChanged,
          excludeZero = _ref15.excludeZero,
          showDescription = _ref15.showDescription,
          showLevelTagInput = _ref15.showLevelTagInput,
          showScorePointLabels = _ref15.showScorePointLabels,
          enableDragAndDrop = _ref15.enableDragAndDrop,
          spellCheck = _ref15.spellCheck,
          width = _ref15.width,
          uploadSoundSupport = _ref15.uploadSoundSupport,
          maxPointsEnabled = _ref15.maxPointsEnabled,
          _ref15$mathMlOptions = _ref15.mathMlOptions,
          mathMlOptions = _ref15$mathMlOptions === void 0 ? {} : _ref15$mathMlOptions,
          maxMaxPoints = _ref15.maxMaxPoints,
          _ref15$expandedPlugin = _ref15.expandedPluginProps,
          expandedPluginProps = _ref15$expandedPlugin === void 0 ? {} : _ref15$expandedPlugin,
          _ref15$labelPluginPro = _ref15.labelPluginProps,
          labelPluginProps = _ref15$labelPluginPro === void 0 ? {} : _ref15$labelPluginPro,
          _ref15$imageSupport = _ref15.imageSupport,
          imageSupport = _ref15$imageSupport === void 0 ? {} : _ref15$imageSupport;

      var _ref16 = scale || {},
          maxPoints = _ref16.maxPoints,
          scorePointsLabels = _ref16.scorePointsLabels,
          traitLabel = _ref16.traitLabel,
          traits = _ref16.traits;

      var _this$state = this.state,
          showDecreaseMaxPointsDialog = _this$state.showDecreaseMaxPointsDialog,
          showDeleteScaleDialog = _this$state.showDeleteScaleDialog,
          showDeleteTraitDialog = _this$state.showDeleteTraitDialog,
          currentPosition = _this$state.currentPosition,
          showRight = _this$state.showRight,
          showLeft = _this$state.showLeft,
          showInfoDialog = _this$state.showInfoDialog,
          infoDialogText = _this$state.infoDialogText;

      var _ref17 = errors || {},
          traitsErrors = _ref17.traitsErrors,
          scorePointsErrors = _ref17.scorePointsErrors;

      var currentScaleTraitsErrors = traitsErrors && traitsErrors[scaleIndex] || {};
      var currentScalePointsLabelsErrors = scorePointsErrors && scorePointsErrors[scaleIndex] || {};
      var scorePointsValues = [];
      var secondaryBlockWidth = parseInt(width) - _common.DragHandleSpace - _common.PrimaryBlockWidth || 320; // 320 is minWidth
      // determining the score points values

      for (var pointValue = maxPoints; pointValue >= excludeZero ? 1 : 0; pointValue -= 1) {
        scorePointsValues.push(pointValue);
      }

      return /*#__PURE__*/_react["default"].createElement("div", {
        key: "scale-".concat(scaleIndex),
        className: classes.scaleWrapper,
        ref: function ref(_ref18) {
          _this2.scaleWrapper = _ref18;
        }
      }, /*#__PURE__*/_react["default"].createElement(_traitsHeader["default"], {
        setSecondaryBlockRef: function setSecondaryBlockRef(ref) {
          if (ref) {
            _this2.secondaryBlockRef = ref;
          }
        },
        key: 'header-key',
        errors: currentScalePointsLabelsErrors,
        traitLabel: traitLabel,
        scorePointsValues: scorePointsValues,
        scorePointsLabels: scorePointsLabels,
        onScaleChange: function onScaleChange(params) {
          return onScaleChanged(scaleIndex, params);
        },
        onTraitLabelChange: function onTraitLabelChange(label) {
          return onScaleChanged(scaleIndex, {
            traitLabel: label
          });
        },
        showStandards: showStandards,
        showDescription: showDescription,
        showLevelTagInput: showLevelTagInput,
        showScorePointLabels: showScorePointLabels,
        maxPoints: maxPoints,
        updateMaxPointsFieldValue: this.updateMaxPointsFieldValue,
        scaleIndex: scaleIndex,
        showDeleteScaleModal: this.showDeleteScaleModal,
        currentPosition: currentPosition,
        secondaryBlockWidth: secondaryBlockWidth,
        spellCheck: spellCheck,
        uploadSoundSupport: uploadSoundSupport,
        maxPointsEnabled: maxPointsEnabled,
        mathMlOptions: mathMlOptions,
        maxMaxPoints: maxMaxPoints,
        expandedPluginProps: expandedPluginProps,
        labelPluginProps: labelPluginProps,
        imageSupport: imageSupport
      }), traits.map(function (trait, index) {
        return /*#__PURE__*/_react["default"].createElement(_trait["default"], {
          key: index,
          index: index,
          error: currentScaleTraitsErrors && currentScaleTraitsErrors[index],
          trait: trait,
          traitLabel: traitLabel || 'Trait',
          scorePointsValues: scorePointsValues,
          scorePointsLabels: scorePointsLabels,
          onTraitRemoved: function onTraitRemoved() {
            return _this2.showDeleteTraitModal(index);
          },
          onTraitChanged: function onTraitChanged(trait) {
            return _this2.onTraitChanged(index, trait);
          },
          onTraitDropped: _this2.onTraitDropped,
          showStandards: showStandards,
          showDescription: showDescription,
          maxPoints: maxPoints,
          currentPosition: currentPosition,
          enableDragAndDrop: enableDragAndDrop,
          secondaryBlockWidth: secondaryBlockWidth,
          spellCheck: spellCheck,
          uploadSoundSupport: uploadSoundSupport,
          mathMlOptions: mathMlOptions,
          expandedPluginProps: expandedPluginProps,
          labelPluginProps: labelPluginProps,
          imageSupport: imageSupport
        });
      }), /*#__PURE__*/_react["default"].createElement(_common.Arrow, {
        width: "".concat(AdjustedBlockWidth / 2, "px"),
        show: showLeft,
        onClick: this.decreasePosition,
        left: "".concat(_common.PrimaryBlockWidth, "px"),
        showLevelTagInput: showLevelTagInput
      }, /*#__PURE__*/_react["default"].createElement(_ArrowBackIos["default"], null)), /*#__PURE__*/_react["default"].createElement(_common.Arrow, {
        width: "".concat(AdjustedBlockWidth / 2, "px"),
        show: showRight,
        onClick: this.increasePosition,
        showLevelTagInput: showLevelTagInput
      }, /*#__PURE__*/_react["default"].createElement(_ArrowForwardIos["default"], null)), /*#__PURE__*/_react["default"].createElement(_common.MultiTraitButton, {
        onClick: this.onTraitAdded
      }, /*#__PURE__*/_react["default"].createElement("div", {
        dangerouslySetInnerHTML: {
          __html: "Add ".concat(traitLabel || ' Trait')
        }
      })), /*#__PURE__*/_react["default"].createElement(_modals.DecreaseMaxPoints, {
        open: !!showDecreaseMaxPointsDialog,
        deleteScorePoints: this.changeMaxPoints,
        cancel: this.hideDecreaseMaxPointsModal
      }), /*#__PURE__*/_react["default"].createElement(_modals.DeleteScale, {
        open: !!showDeleteScaleDialog,
        scaleIndex: scaleIndex,
        deleteScale: this.deleteScale,
        cancel: this.hideDeleteScaleModal
      }), /*#__PURE__*/_react["default"].createElement(_modals.DeleteTrait, {
        open: !!showDeleteTraitDialog,
        deleteTrait: this.onTraitRemoved,
        cancel: this.hideDeleteTraitModal,
        traitLabel: traitLabel.toLowerCase()
      }), /*#__PURE__*/_react["default"].createElement(_modals.InfoDialog, {
        open: showInfoDialog,
        text: infoDialogText,
        onClose: function onClose() {
          return _this2.set({
            showInfoDialog: false
          });
        }
      }));
    }
  }]);
  return Scale;
}(_react["default"].Component);

exports.Scale = Scale;
Scale.propTypes = {
  classes: _propTypes["default"].object,
  errors: _propTypes["default"].object,
  scale: _propTypes["default"].shape({
    maxPoints: _propTypes["default"].number,
    scorePointsLabels: _propTypes["default"].arrayOf(_propTypes["default"].string),
    traitLabel: _propTypes["default"].string,
    traits: _propTypes["default"].arrayOf(_propTypes["default"].shape({
      name: _propTypes["default"].string,
      standards: _propTypes["default"].arrayOf(_propTypes["default"].string),
      scorePointsDescriptors: _propTypes["default"].arrayOf(_propTypes["default"].string),
      description: _propTypes["default"].string
    }))
  }),
  width: _propTypes["default"].string,
  excludeZero: _propTypes["default"].bool,
  scaleIndex: _propTypes["default"].number,
  onScaleChanged: _propTypes["default"].func,
  onScaleRemoved: _propTypes["default"].func,
  showStandards: _propTypes["default"].bool,
  showLevelTagInput: _propTypes["default"].bool,
  showDescription: _propTypes["default"].bool,
  uploadSoundSupport: _propTypes["default"].object,
  showScorePointLabels: _propTypes["default"].bool,
  enableDragAndDrop: _propTypes["default"].bool,
  expandedPluginProps: _propTypes["default"].object,
  labelPluginProps: _propTypes["default"].object
};

var _default = (0, _drag.withDragContext)((0, _styles.withStyles)(styles)(Scale));

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