"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = 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 _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));

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

var _pieConfigureEvents = require("@pie-framework/pie-configure-events");

var _react = _interopRequireDefault(require("react"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _main = _interopRequireDefault(require("./main"));

var _defaults = _interopRequireDefault(require("./defaults"));

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

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; } }

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; }

var modelWithDefaults = function modelWithDefaults(m) {
  return _objectSpread(_objectSpread({}, _defaults["default"].model), m);
};

var configurationWithDefaults = function configurationWithDefaults(c) {
  return _objectSpread(_objectSpread({}, _defaults["default"].configuration), c);
};

var MultiTraitRubricElement = /*#__PURE__*/function (_HTMLElement) {
  (0, _inherits2["default"])(MultiTraitRubricElement, _HTMLElement);

  var _super = _createSuper(MultiTraitRubricElement);

  function MultiTraitRubricElement() {
    var _this;

    (0, _classCallCheck2["default"])(this, MultiTraitRubricElement);
    _this = _super.call(this);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateModelAccordingToReceivedProps", function (m) {
      var currentModel = _objectSpread({}, _this._model);

      if (!m) {
        return currentModel;
      }

      var validatedModel = _objectSpread({}, m);

      var _ref = validatedModel || {},
          scales = _ref.scales,
          excludeZero = _ref.excludeZero;

      (scales || []).forEach(function (scale) {
        if (!scale) {
          scale = {
            scorePointsLabels: [],
            traits: []
          };
        }

        var _ref2 = scale || {},
            maxPoints = _ref2.maxPoints;

        scale.scorePointsLabels = (0, _toConsumableArray2["default"])(scale.scorePointsLabels || []);
        scale.traits = (0, _toConsumableArray2["default"])(scale.traits || []);
        var howManyScorePointLabelsShouldHave = excludeZero ? maxPoints : maxPoints + 1;
        var howManyScorePointLabelsItHas = scale.scorePointsLabels.length;

        if (howManyScorePointLabelsItHas !== howManyScorePointLabelsShouldHave) {
          if (howManyScorePointLabelsItHas < howManyScorePointLabelsShouldHave) {
            for (var i = 0; i < howManyScorePointLabelsShouldHave - howManyScorePointLabelsItHas; i++) {
              scale.scorePointsLabels.push('');
            }
          } else {
            scale.scorePointsLabels = scale.scorePointsLabels.slice(0, howManyScorePointLabelsShouldHave);
          }
        }

        (scale.traits || []).forEach(function (trait) {
          if (!trait) {
            trait = {
              scorePointsDescriptors: []
            };
          }

          trait.scorePointsDescriptors = (0, _toConsumableArray2["default"])(trait.scorePointsDescriptors || []);
          var howManyScorePointDescriptorsItHas = trait.scorePointsDescriptors.length;

          if (howManyScorePointDescriptorsItHas !== howManyScorePointLabelsShouldHave) {
            if (howManyScorePointDescriptorsItHas < howManyScorePointLabelsShouldHave) {
              for (var _i = 0; _i < howManyScorePointLabelsShouldHave - howManyScorePointDescriptorsItHas; _i++) {
                trait.scorePointsDescriptors.push('');
              }
            } else {
              trait.scorePointsDescriptors = trait.scorePointsDescriptors.slice(0, howManyScorePointLabelsShouldHave);
            }
          }
        });
      });

      if (validatedModel.excludeZero) {
        // check if any scale has maxPoints set to 1
        var shouldAddColumn0 = validatedModel.scales.some(function (scale) {
          return scale.maxPoints === 1;
        });

        if (shouldAddColumn0) {
          // excludeZero should be false and disabled when maxPoints is 1
          validatedModel.excludeZero = false; // add column 0 for all scales

          validatedModel.scales = (0, _utils.addOrRemoveScaleColumn)(scales, _modals.excludeZeroTypes.add0);
        }
      }

      return validatedModel;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onModelChanged", function (m) {
      _this._model = _this.updateModelAccordingToReceivedProps(modelWithDefaults(m));

      _this._render();

      _this.dispatchEvent(new _pieConfigureEvents.ModelUpdatedEvent(_this._model, false));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onConfigurationChanged", function (c) {
      _this._configuration = configurationWithDefaults(c);

      _this._render();
    });
    _this._model = modelWithDefaults();
    _this._configuration = configurationWithDefaults();
    return _this;
  }

  (0, _createClass2["default"])(MultiTraitRubricElement, [{
    key: "model",
    set: function set(m) {
      this._model = this.updateModelAccordingToReceivedProps(modelWithDefaults(m));

      this._render();
    }
  }, {
    key: "configuration",
    set: function set(c) {
      this._configuration = configurationWithDefaults(c);

      this._render();
    }
  }, {
    key: "insertSound",
    value: function insertSound(handler) {
      this.dispatchEvent(new _pieConfigureEvents.InsertSoundEvent(handler));
    }
  }, {
    key: "onDeleteSound",
    value: function onDeleteSound(src, done) {
      this.dispatchEvent(new _pieConfigureEvents.DeleteSoundEvent(src, done));
    }
  }, {
    key: "insertImage",
    value: function insertImage(handler) {
      this.dispatchEvent(new _pieConfigureEvents.InsertImageEvent(handler));
    }
  }, {
    key: "onDeleteImage",
    value: function onDeleteImage(src, done) {
      this.dispatchEvent(new _pieConfigureEvents.DeleteImageEvent(src, done));
    }
  }, {
    key: "_render",
    value: function _render() {
      if (this._model) {
        var element = /*#__PURE__*/_react["default"].createElement(_main["default"], {
          model: this._model,
          configuration: this._configuration,
          onModelChanged: this.onModelChanged,
          onConfigurationChanged: this.onConfigurationChanged,
          uploadSoundSupport: {
            add: this.insertSound.bind(this),
            "delete": this.onDeleteSound.bind(this)
          },
          imageSupport: {
            add: this.insertImage.bind(this),
            "delete": this.onDeleteImage.bind(this)
          }
        });

        _reactDom["default"].render(element, this);
      }
    }
  }]);
  return MultiTraitRubricElement;
}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(HTMLElement));

exports["default"] = MultiTraitRubricElement;
//# sourceMappingURL=index.js.map