"use strict";

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

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

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 _react = _interopRequireDefault(require("react"));

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

var _debug = _interopRequireDefault(require("debug"));

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

var _isArray = _interopRequireDefault(require("lodash/isArray"));

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

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

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

var _markupUtils = require("./markupUtils");

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 log = (0, _debug["default"])('explicit-constructed-response:configure');

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

  var _super = _createSuper(ExplicitConstructedResponse);

  function ExplicitConstructedResponse() {
    var _this;

    (0, _classCallCheck2["default"])(this, ExplicitConstructedResponse);
    _this = _super.call(this);
    _this._model = ExplicitConstructedResponse.prepareModel();
    _this._configuration = _defaults2["default"].configuration;
    _this.onModelChanged = _this.onModelChanged.bind((0, _assertThisInitialized2["default"])(_this));
    _this.onConfigurationChanged = _this.onConfigurationChanged.bind((0, _assertThisInitialized2["default"])(_this));
    return _this;
  }

  (0, _createClass2["default"])(ExplicitConstructedResponse, [{
    key: "model",
    set: function set(s) {
      this._model = ExplicitConstructedResponse.prepareModel(s);

      if (this._model.responseAreaInputConfiguration) {
        var _this$_configuration$;

        this._model.responseAreaInputConfiguration = (_this$_configuration$ = this._configuration.responseAreaInputConfiguration) === null || _this$_configuration$ === void 0 ? void 0 : _this$_configuration$.inputConfiguration;
      }

      this._render();
    }
  }, {
    key: "configuration",
    set: function set(c) {
      var _c$language,
          _this2 = this;

      this._configuration = (0, _defaults["default"])(c, _defaults2["default"].configuration); // if language:enabled is true, then the corresponding default item model should include a language value;
      // if it is false, then the language field should be omitted from the item model.
      // if a default item model includes a language value (e.g., en_US) and the corresponding authoring view settings have language:settings = true,
      // then (a) language:enabled should also be true, and (b) that default language value should be represented in languageChoices[] (as a key).

      if ((_c$language = c.language) !== null && _c$language !== void 0 && _c$language.enabled) {
        var _c$languageChoices, _c$languageChoices$op;

        if ((_c$languageChoices = c.languageChoices) !== null && _c$languageChoices !== void 0 && (_c$languageChoices$op = _c$languageChoices.options) !== null && _c$languageChoices$op !== void 0 && _c$languageChoices$op.length) {
          this._model.language = c.languageChoices.options[0].value;
        }
      } else if (c.language.settings && this._model.language) {
        this._configuration.language.enabled = true;

        if (!this._configuration.languageChoices.options || !this._configuration.languageChoices.options.length) {
          this._configuration.languageChoices.options = [];
        } // check if the language is already included in the languageChoices.options array
        // and if not, then add it.


        if (!this._configuration.languageChoices.options.find(function (option) {
          return option.value === _this2._model.language;
        })) {
          this._configuration.languageChoices.options.push({
            value: this._model.language,
            label: this._model.language
          });
        }
      } else {
        delete this._model.language;
      }

      this._render();
    }
  }, {
    key: "disableSidePanel",
    set: function set(s) {
      this._disableSidePanel = s;

      this._render();
    }
  }, {
    key: "dispatchModelUpdated",
    value: function dispatchModelUpdated(reset) {
      var resetValue = !!reset;
      this.dispatchEvent(new _pieConfigureEvents.ModelUpdatedEvent(this._model, resetValue));
    }
  }, {
    key: "onModelChanged",
    value: function onModelChanged(m, reset) {
      this._model = ExplicitConstructedResponse.prepareModel(m);

      this._render();

      this.dispatchModelUpdated(reset);
    }
  }, {
    key: "onConfigurationChanged",
    value: function onConfigurationChanged(c) {
      var _this$_model, _this$_configuration, _this$_configuration$2;

      var previousInputConfig = (_this$_model = this._model) === null || _this$_model === void 0 ? void 0 : _this$_model.responseAreaInputConfiguration;
      this._configuration = c;
      var newInputConfig = (_this$_configuration = this._configuration) === null || _this$_configuration === void 0 ? void 0 : (_this$_configuration$2 = _this$_configuration.responseAreaInputConfiguration) === null || _this$_configuration$2 === void 0 ? void 0 : _this$_configuration$2.inputConfiguration;

      if (previousInputConfig !== newInputConfig) {
        this._model = _objectSpread(_objectSpread({}, this._model), {}, {
          responseAreaInputConfiguration: newInputConfig
        });
        this.onModelChanged(this._model);
      } else {
        this._render();
      }
    }
    /** @param {done, progress, file} handler */

  }, {
    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: "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: "_render",
    value: function _render() {
      log('_render');

      var element = /*#__PURE__*/_react["default"].createElement(_main["default"], {
        model: this._model,
        configuration: this._configuration,
        onModelChanged: this.onModelChanged,
        onConfigurationChanged: this.onConfigurationChanged,
        disableSidePanel: this._disableSidePanel,
        imageSupport: {
          add: this.insertImage.bind(this),
          "delete": this.onDeleteImage.bind(this)
        },
        uploadSoundSupport: {
          add: this.insertSound.bind(this),
          "delete": this.onDeleteSound.bind(this)
        }
      });

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

exports["default"] = ExplicitConstructedResponse;
(0, _defineProperty2["default"])(ExplicitConstructedResponse, "prepareModel", function () {
  var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var joinedObj = _objectSpread(_objectSpread({}, _defaults2["default"].model), model);

  var slateMarkup = joinedObj.slateMarkup || (0, _markupUtils.createSlateMarkup)(joinedObj.markup, joinedObj.choices);
  var processedMarkup = (0, _markupUtils.processMarkup)(slateMarkup); // this was added to treat an exception, when the model has choices without the "value" property
  // like: { label: 'test' }

  if (joinedObj.choices) {
    Object.keys(joinedObj.choices).forEach(function (key) {
      if ((0, _isArray["default"])(joinedObj.choices[key])) {
        joinedObj.choices[key] = (joinedObj.choices[key] || []).map(function (item, index) {
          if (!item.value) {
            log('Choice does not contain "value" property, which is required.', item);
            return _objectSpread({
              value: "".concat(index)
            }, item);
          }

          return item;
        });
      }
    });
  }

  return _objectSpread(_objectSpread({}, joinedObj), {}, {
    slateMarkup: slateMarkup,
    markup: processedMarkup
  });
});
//# sourceMappingURL=index.js.map