"use strict";

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

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

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

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 _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var _isEmpty = _interopRequireDefault(require("lodash/isEmpty"));

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

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

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

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

var _scale = _interopRequireDefault(require("./scale"));

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

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

var _utils = require("./utils");

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 Panel = _configUi.settings.Panel,
    toggle = _configUi.settings.toggle;
var MIN_WIDTH = '650px';

var styles = function styles(theme) {
  return {
    design: {
      fontFamily: 'Cerebri Sans',
      fontSize: theme.typography.fontSize
    }
  };
};

var ShowModal = function ShowModal(_ref) {
  var showExcludeZeroDialog = _ref.showExcludeZeroDialog,
      excludeZero = _ref.excludeZero,
      changeExcludeZero = _ref.changeExcludeZero,
      cancel = _ref.cancel;

  if (showExcludeZeroDialog && !excludeZero) {
    return /*#__PURE__*/_react["default"].createElement(_modals.ExcludeZeroDialog, {
      open: showExcludeZeroDialog && !excludeZero,
      changeExcludeZero: changeExcludeZero,
      cancel: cancel
    });
  } else if (showExcludeZeroDialog && excludeZero) {
    return /*#__PURE__*/_react["default"].createElement(_modals.IncludeZeroDialog, {
      open: showExcludeZeroDialog && excludeZero,
      changeExcludeZero: changeExcludeZero,
      cancel: cancel
    });
  } else {
    return null;
  }
};

ShowModal.propTypes = {
  showExcludeZeroDialog: _propTypes["default"].bool,
  excludeZero: _propTypes["default"].bool,
  changeExcludeZero: _propTypes["default"].func,
  cancel: _propTypes["default"].func
};

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

  var _super = _createSuper(Main);

  function Main(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Main);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "state", {
      showDecreaseMaxPointsDialog: false,
      showDeleteScaleDialog: false,
      showDeleteTraitDialog: false,
      showExcludeZeroDialog: false,
      showInfoDialog: false,
      infoDialogText: '',
      adjustedWidth: MIN_WIDTH,
      initialUpdateCompleted: false // flag to track the initial update of the div width

    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateDivWidthDebounced", (0, _debounce["default"])(function () {
      return _this.updateDivWidth();
    }, 50));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onScaleAdded", function () {
      var _scales$;

      var _this$props = _this.props,
          model = _this$props.model,
          onModelChanged = _this$props.onModelChanged,
          configuration = _this$props.configuration;

      var _ref2 = model || {},
          scales = _ref2.scales,
          excludeZero = _ref2.excludeZero;

      var _ref3 = configuration || {},
          maxNoOfScales = _ref3.maxNoOfScales;

      var _ref4 = configuration || '',
          defaultTraitLabel = _ref4.defaultTraitLabel;

      if (!scales.length) {
        scales = [];
      } // if no default trait label is defined, take the trait label of the first scale


      defaultTraitLabel = typeof defaultTraitLabel === 'string' ? defaultTraitLabel : ((_scales$ = scales[0]) === null || _scales$ === void 0 ? void 0 : _scales$.traitLabel) || '';

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

        return false;
      }

      scales.push({
        maxPoints: 1,
        scorePointsLabels: excludeZero ? [''] : ['', ''],
        traitLabel: defaultTraitLabel,
        traits: []
      });
      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        scales: scales
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onScaleChanged", function (scaleIndex, params) {
      var _this$props2 = _this.props,
          model = _this$props2.model,
          onModelChanged = _this$props2.onModelChanged;
      var scales = (0, _cloneDeep["default"])((model || {}).scales);
      if (scaleIndex < 0 || scaleIndex >= scales.length || (0, _isEmpty["default"])(params)) return false;
      Object.keys(params).forEach(function (key) {
        scales[scaleIndex][key] = params[key];
      });

      if (model.excludeZero && params.maxPoints === 1) {
        // excludeZero should be false and disabled when maxPoints is 1 for any scale
        model.excludeZero = false;
        scales = (0, _utils.addOrRemoveScaleColumn)(scales, _modals.excludeZeroTypes.add0);
      }

      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        scales: scales
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onScaleRemoved", function (scaleIndex) {
      var _this$props3 = _this.props,
          model = _this$props3.model,
          onModelChanged = _this$props3.onModelChanged,
          configuration = _this$props3.configuration;

      var _ref5 = model || {},
          scales = _ref5.scales;

      var _ref6 = configuration || {},
          minNoOfScales = _ref6.minNoOfScales;

      if (scaleIndex < 0 || scaleIndex >= scales.length) return false;

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

        return false;
      }

      scales = [].concat((0, _toConsumableArray2["default"])(scales.slice(0, scaleIndex)), (0, _toConsumableArray2["default"])(scales.slice(scaleIndex + 1)));
      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        scales: scales
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onHalfScoringChanged", function () {
      var _this$props4 = _this.props,
          model = _this$props4.model,
          onModelChanged = _this$props4.onModelChanged;

      var _ref7 = model || {},
          halfScoring = _ref7.halfScoring;

      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        halfScoring: !halfScoring
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onVisibleToStudentChanged", function () {
      var _this$props5 = _this.props,
          model = _this$props5.model,
          onModelChanged = _this$props5.onModelChanged;

      var _ref8 = model || {},
          visibleToStudent = _ref8.visibleToStudent;

      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        visibleToStudent: !visibleToStudent
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "set", function (newState) {
      return _this.setState(newState);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeShowScorePointLabels", function () {
      var _ref9 = _this.props || {},
          model = _ref9.model,
          onModelChanged = _ref9.onModelChanged;

      var _ref10 = model || {},
          pointLabels = _ref10.pointLabels;

      pointLabels = !pointLabels;
      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        pointLabels: pointLabels
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeShowDescription", function () {
      var _ref11 = _this.props || {},
          model = _ref11.model,
          onModelChanged = _ref11.onModelChanged;

      var _ref12 = model || {},
          description = _ref12.description;

      description = !description;
      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        description: description
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeShowStandards", function () {
      var _ref13 = _this.props || {},
          model = _ref13.model,
          onModelChanged = _ref13.onModelChanged;

      var _ref14 = model || {},
          standards = _ref14.standards;

      standards = !standards;
      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        standards: standards
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "showToggleExcludeZeroModal", function () {
      return _this.set({
        showExcludeZeroDialog: true
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "hideToggleExcludeZeroModal", function () {
      _this.set({
        showExcludeZeroDialog: false
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onCloseInfoDialog", function () {
      return _this.set({
        showInfoDialog: false
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeExcludeZero", function (excludeZeroType) {
      var _ref15 = _this.props || {},
          model = _ref15.model,
          onModelChanged = _ref15.onModelChanged;

      var _ref16 = model || {},
          scales = _ref16.scales;

      var _ref17 = model || {},
          excludeZero = _ref17.excludeZero;

      if (!scales || !scales.length) return;
      excludeZero = !excludeZero;
      var newScales = (0, _utils.addOrRemoveScaleColumn)(scales, excludeZeroType);
      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        scales: newScales,
        excludeZero: excludeZero
      }));

      _this.hideToggleExcludeZeroModal();
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onModelChanged", function (updatedModel, updatedProperty) {
      var _ref18 = _this.props || {},
          onModelChanged = _ref18.onModelChanged;

      if (updatedProperty === 'excludeZero') {
        _this.showToggleExcludeZeroModal();
      } else {
        onModelChanged(updatedModel);
      }
    });
    _this.divRef = /*#__PURE__*/_react["default"].createRef();
    _this.updateDivWidth = _this.updateDivWidth.bind((0, _assertThisInitialized2["default"])(_this));
    return _this;
  }

  (0, _createClass2["default"])(Main, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      window.addEventListener('resize', this.updateDivWidthDebounced);
      window.addEventListener('load', this.updateDivWidth); // delay updateDivWidth to avoid having this.divRef.current = null at first load

      setTimeout(this.updateDivWidth, 0);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      window.removeEventListener('resize', this.updateDivWidthDebounced);
      window.removeEventListener('load', this.updateDivWidth);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      if (!this.state.initialUpdateCompleted) {
        this.updateDivWidth();
        this.setState({
          initialUpdateCompleted: true
        });
      }
    }
  }, {
    key: "updateDivWidth",
    value: function updateDivWidth() {
      if (this.divRef && this.divRef.current) {
        var divWidth = this.divRef.current.offsetWidth;

        if (divWidth !== this.state.adjustedWidth) {
          this.set({
            adjustedWidth: divWidth
          });
        }
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _ref19 = this.props || {},
          model = _ref19.model,
          configuration = _ref19.configuration,
          onConfigurationChanged = _ref19.onConfigurationChanged,
          uploadSoundSupport = _ref19.uploadSoundSupport,
          imageSupport = _ref19.imageSupport;

      var _ref20 = configuration || {},
          addScale = _ref20.addScale,
          _ref20$baseInputConfi = _ref20.baseInputConfiguration,
          baseInputConfiguration = _ref20$baseInputConfi === void 0 ? {} : _ref20$baseInputConfi,
          dragAndDrop = _ref20.dragAndDrop,
          _ref20$contentDimensi = _ref20.contentDimensions,
          contentDimensions = _ref20$contentDimensi === void 0 ? {} : _ref20$contentDimensi,
          showDescription = _ref20.showDescription,
          showExcludeZero = _ref20.showExcludeZero,
          showLevelTagInput = _ref20.showLevelTagInput,
          showStandards = _ref20.showStandards,
          showHalfScoring = _ref20.showHalfScoring,
          showMaxPoint = _ref20.showMaxPoint,
          showScorePointLabels = _ref20.showScorePointLabels,
          showVisibleToStudent = _ref20.showVisibleToStudent,
          _ref20$spellCheck = _ref20.spellCheck,
          spellCheck = _ref20$spellCheck === void 0 ? {} : _ref20$spellCheck,
          settingsPanelDisabled = _ref20.settingsPanelDisabled,
          maxNoOfTraits = _ref20.maxNoOfTraits,
          minNoOfTraits = _ref20.minNoOfTraits,
          width = _ref20.width,
          _ref20$mathMlOptions = _ref20.mathMlOptions,
          mathMlOptions = _ref20$mathMlOptions === void 0 ? {} : _ref20$mathMlOptions,
          maxMaxPoints = _ref20.maxMaxPoints,
          _ref20$expandedInput = _ref20.expandedInput,
          expandedInput = _ref20$expandedInput === void 0 ? {} : _ref20$expandedInput,
          _ref20$labelInput = _ref20.labelInput,
          labelInput = _ref20$labelInput === void 0 ? {} : _ref20$labelInput;

      var _ref21 = model || {},
          errors = _ref21.errors,
          extraCSSRules = _ref21.extraCSSRules,
          scales = _ref21.scales,
          excludeZero = _ref21.excludeZero,
          description = _ref21.description,
          pointLabels = _ref21.pointLabels,
          standards = _ref21.standards,
          spellCheckEnabled = _ref21.spellCheckEnabled,
          maxPointsEnabled = _ref21.maxPointsEnabled,
          addScaleEnabled = _ref21.addScaleEnabled;

      var _ref22 = this.state || {},
          showExcludeZeroDialog = _ref22.showExcludeZeroDialog,
          showInfoDialog = _ref22.showInfoDialog,
          infoDialogText = _ref22.infoDialogText,
          adjustedWidth = _ref22.adjustedWidth; // excludeZero should be false and disabled when maxPoints is 1 for any scale


      var disabledExcludeZero = scales === null || scales === void 0 ? void 0 : scales.some(function (scale) {
        return scale.maxPoints === 1;
      });
      var panelSettings = {
        standards: showStandards.settings && toggle(showStandards.label),
        'showLevelTagInput.enabled': showLevelTagInput.settings && toggle(showLevelTagInput.label, true),
        visibleToStudent: showVisibleToStudent.settings && toggle(showVisibleToStudent.label),
        excludeZero: showExcludeZero.settings && toggle(showExcludeZero.label, false, disabledExcludeZero),
        halfScoring: showHalfScoring.settings && toggle(showHalfScoring.label),
        'dragAndDrop.enabled': dragAndDrop.settings && toggle(dragAndDrop.label, true)
      };
      var panelProperties = {
        description: showDescription.settings && toggle(showDescription.label),
        pointLabels: showScorePointLabels.settings && toggle(showScorePointLabels.label),
        spellCheckEnabled: spellCheck.settings && toggle(spellCheck.label),
        maxPointsEnabled: showMaxPoint.settings && toggle(showMaxPoint.label),
        addScaleEnabled: addScale.settings && toggle(addScale.label)
      };

      var getPluginProps = function getPluginProps(props) {
        return Object.assign(_objectSpread({}, baseInputConfiguration), props || {});
      };

      return /*#__PURE__*/_react["default"].createElement(_configUi.layout.ConfigLayout, {
        extraCSSRules: extraCSSRules,
        dimensions: contentDimensions,
        hideSettings: settingsPanelDisabled,
        settings: /*#__PURE__*/_react["default"].createElement(Panel, {
          model: model,
          onChangeModel: this.onModelChanged,
          configuration: configuration,
          onChangeConfiguration: onConfigurationChanged,
          groups: {
            Settings: panelSettings,
            Properties: panelProperties
          },
          modal: /*#__PURE__*/_react["default"].createElement(ShowModal, {
            showExcludeZeroDialog: showExcludeZeroDialog,
            excludeZero: excludeZero,
            changeExcludeZero: this.changeExcludeZero,
            cancel: this.hideToggleExcludeZeroModal
          })
        })
      }, /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          width: '100%'
        },
        ref: this.divRef
      }), /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          width: width || adjustedWidth
        }
      }, (scales || []).map(function (scale, scaleIndex) {
        return /*#__PURE__*/_react["default"].createElement(_scale["default"], (0, _extends2["default"])({
          key: "scale-".concat(scaleIndex),
          scale: scale,
          scaleIndex: scaleIndex,
          errors: errors,
          onScaleRemoved: _this2.onScaleRemoved,
          onScaleChanged: _this2.onScaleChanged,
          showStandards: standards,
          showScorePointLabels: pointLabels,
          showDescription: description,
          showLevelTagInput: showLevelTagInput.enabled,
          excludeZero: excludeZero,
          enableDragAndDrop: dragAndDrop.enabled,
          spellCheck: spellCheckEnabled,
          width: adjustedWidth,
          uploadSoundSupport: uploadSoundSupport,
          maxPointsEnabled: maxPointsEnabled,
          maxNoOfTraits: maxNoOfTraits,
          minNoOfTraits: minNoOfTraits,
          imageSupport: imageSupport
        }, _this2.props, {
          classes: {},
          mathMlOptions: mathMlOptions,
          maxMaxPoints: maxMaxPoints,
          expandedPluginProps: getPluginProps(expandedInput === null || expandedInput === void 0 ? void 0 : expandedInput.inputConfiguration),
          labelPluginProps: getPluginProps(labelInput === null || labelInput === void 0 ? void 0 : labelInput.inputConfiguration)
        }));
      }), addScaleEnabled && /*#__PURE__*/_react["default"].createElement(_common.MultiTraitButton, {
        onClick: this.onScaleAdded
      }, "Add Scale")), /*#__PURE__*/_react["default"].createElement(_modals.InfoDialog, {
        open: showInfoDialog,
        text: infoDialogText,
        onClose: function onClose() {
          return _this2.set({
            showInfoDialog: false
          });
        }
      }));
    }
  }]);
  return Main;
}(_react["default"].Component);

exports.Main = Main;
Main.propTypes = {
  classes: _propTypes["default"].object,
  model: _propTypes["default"].object,
  uploadSoundSupport: _propTypes["default"].object,
  configuration: _propTypes["default"].object,
  onModelChanged: _propTypes["default"].func,
  onConfigurationChanged: _propTypes["default"].func,
  imageSupport: _propTypes["default"].shape({
    add: _propTypes["default"].func.isRequired,
    "delete": _propTypes["default"].func.isRequired
  })
};

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

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