"use strict";

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

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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 _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

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

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _immutable = require("immutable");

var _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));

var _set = _interopRequireDefault(require("lodash/fp/set"));

var _Modal = _interopRequireWildcard(require("@instructure/quiz-common/lib/components/Modal"));

var _Heading = _interopRequireDefault(require("@instructure/ui-elements/lib/components/Heading"));

var _Button = _interopRequireDefault(require("@instructure/ui-buttons/lib/components/Button"));

var _CloseButton = _interopRequireDefault(require("@instructure/ui-buttons/lib/components/CloseButton"));

var _Select = _interopRequireDefault(require("@instructure/ui-forms/lib/components/Select"));

var _Grid = _interopRequireWildcard(require("@instructure/ui-layout/lib/components/Grid"));

var _lib = _interopRequireDefault(require("@instructure/ui-themeable/lib"));

var _constants = require("@instructure/quiz-common/lib/constants");

var _ElementsForSelectors = _interopRequireDefault(require("../../../common/util/ElementsForSelectors"));

var _CustomPropTypes = _interopRequireDefault(require("../../../common/util/CustomPropTypes"));

var _peopleList = _interopRequireDefault(require("./peopleList"));

var _asyncSearch = _interopRequireDefault(require("./asyncSearch"));

var _Spinner = _interopRequireDefault(require("../../../common/components/shared/spinner/Spinner"));

var _theme = _interopRequireDefault(require("./theme"));

var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/lib/format-message"));

var _dec, _class, _class2, _temp;

var styles = {
  componentId: 'eeOol',
  template: function template(theme) {
    return "\n\n.quiz-core__SharingModal--separator {\n  width: 100%;\n  margin: ".concat(theme.separatorMargin || 'inherit', " 0;\n  padding: 0;\n  border-bottom: solid ").concat(theme.separatorBorderWidth || 'inherit', ";\n  border-color: ").concat(theme.separatorColor || 'inherit', ";\n}\n\n.quiz-core__SharingModal--labelRemoved {\n  text-decoration: line-through;\n}\n");
  },
  'separator': 'quiz-core__SharingModal--separator',
  'labelRemoved': 'quiz-core__SharingModal--labelRemoved'
};

var noop = function noop() {};

var SharingModalPresenter = (_dec = (0, _lib.default)(_theme.default, styles), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(SharingModalPresenter, _Component);

  function SharingModalPresenter() {
    var _getPrototypeOf2;

    var _this;

    (0, _classCallCheck2.default)(this, SharingModalPresenter);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(SharingModalPresenter)).call.apply(_getPrototypeOf2, [this].concat(args)));
    _this.state = {
      people: (0, _immutable.List)(),
      newPeople: (0, _immutable.List)(),
      searchSelection: [],
      peopleToRemove: []
    };
    _this.peopleListRef = null;
    _this.shareButtonRef = null;

    _this.applicationElement = function () {
      return (0, _ElementsForSelectors.default)(_this.props.appContainer);
    };

    _this.handleDismiss = function () {
      _this.props.onDismiss();

      if (_this.props.modalTrigger) {
        _this.props.modalTrigger.focus();
      } // removes the owner's temporary sharedBank record


      _this.props.removeSharedBank('-1');
    };

    _this.handleSubmit = function () {
      // calls the sharedBank api with the new people you shared the current bank with
      var newPeople = _this.state.newPeople.filter(function (person) {
        return !_this.state.peopleToRemove.includes(person.get('id'));
      });

      var promises = [];
      newPeople.forEach(function (person) {
        _this.props.onShare(person.toJS());

        var sharedBank = {
          userUuid: person.get('userUuid'),
          bankId: _this.props.bank.id,
          permission: _constants.CAN_EDIT
        };
        promises.push(_this.props.shareBank(sharedBank, _this.props.getUserInfo));
      }); // call the update api if any shared bank was updated/eliminated

      _this.state.peopleToRemove.forEach(function (sharedBankId) {
        var sharedBank = _this.props.sharedBanks.find(function (sharedBank) {
          return sharedBank.get('id') === sharedBankId;
        });

        if (sharedBank) {
          promises.push(_this.props.updateSharedBankPermission(_this.props.bank.id, sharedBankId, _constants.REMOVED_ACCESS));
        }
      }); // waits till all the calls to the shareBank and updateSharedBank apis have completed


      Promise.all(promises).then(function (values) {
        // calls getBank for the current bank to update the sharedCount
        _this.props.getBank(_this.props.bank.id);
      });

      _this.setState({
        newPeople: (0, _immutable.List)()
      });

      _this.handleDismiss();
    };

    _this.handleSearchSelectionChange = function (searchSelection) {
      return _this.setState({
        searchSelection: searchSelection
      });
    };

    _this.handlePersonRemove = function (id, undoRemove) {
      if (undoRemove) {
        _this.setState({
          peopleToRemove: _this.state.peopleToRemove.filter(function (sharedBankId) {
            return sharedBankId !== id;
          })
        });
      } else {
        _this.setState({
          peopleToRemove: [].concat((0, _toConsumableArray2.default)(_this.state.peopleToRemove), [id])
        });
      }
    };

    _this.handleSearchPermissionChange = function (_ref) {
      var value = _ref.target.value;
      return _this.setState({
        searchPermission: value
      });
    };

    _this.handleSearchFilter = function (searchResults) {
      return searchResults.filter(function (result) {
        return !_this.state.people.some(function (person) {
          return person.get('userUuid') === result.value;
        }) && (result.value !== _this.props.bank.owner || _this.props.bank.sharedCount > 0);
      });
    };

    _this.handleShare = function () {
      var newPeople = (0, _immutable.List)(_this.state.searchSelection.map(function (person) {
        return (0, _immutable.Map)({
          id: person.uuid,
          userUuid: person.uuid,
          fullName: person.fullName,
          avatar: person.avatar,
          permission: _constants.CAN_EDIT
        });
      }));

      _this.setState({
        searchSelection: [],
        people: newPeople.concat(_this.state.people),
        newPeople: newPeople.concat(_this.state.newPeople)
      });
    };

    _this.handlePersonPermissionChange = function (index, permission) {
      return _this.setState({
        people: (0, _set.default)("[".concat(index, "].permission"), permission, _this.state.people)
      });
    };

    _this.handlePeopleListRef = function (node) {
      _this.peopleListRef = node;
    };

    _this.handleShareButtonRef = function (node) {
      _this.shareButtonRef = node;
    };

    return _this;
  }

  (0, _createClass2.default)(SharingModalPresenter, [{
    key: "componentDidMount",
    // =============
    //   LIFECYCLE
    // =============
    value: function componentDidMount() {
      var size = this.props.sharedBanks.size;

      if (size >= 0 && size !== this.props.bank.sharedCount || size === 0) {
        this.props.getSharedBanks(this.props.bank, this.props.getUserInfo);
      } else {
        // eslint-disable-next-line react/no-did-mount-set-state
        this.setState({
          people: this.props.sharedBanks
        });
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      this.setState({
        people: nextProps.sharedBanks
      });
    } // =============
    //   HANDLERS
    // =============

  }, {
    key: "renderSearchSection",
    // =============
    //   RENDERING
    // =============
    value: function renderSearchSection() {
      return _react.default.createElement(_Grid.default, {
        vAlign: "bottom",
        colSpacing: "small"
      }, _react.default.createElement(_Grid.GridRow, null, _react.default.createElement(_Grid.GridCol, null, _react.default.createElement(_asyncSearch.default, {
        search: this.props.search,
        minChars: this.props.minChars,
        onSelectionChange: this.handleSearchSelectionChange,
        selectedOption: this.state.searchSelection,
        selectionFilter: this.handleSearchFilter
      })), false && _react.default.createElement(_Grid.GridCol, {
        width: "auto"
      }, _react.default.createElement(_Select.default, {
        onChange: this.handleSearchPermissionChange,
        value: this.state.searchPermission,
        label: "Accesso",
        disabled: true
      }, _react.default.createElement("option", {
        value: _constants.CAN_EDIT
      }, "Pu\xF2 modificare"), _react.default.createElement("option", {
        value: _constants.READ_ONLY
      }, "Solo lettura"))), _react.default.createElement(_Grid.GridCol, {
        width: "auto"
      }, _react.default.createElement(_Button.default, {
        "data-automation": "sdk-shared-bank-add-user-button",
        ref: this.handleShareButtonRef,
        onClick: this.handleShare,
        variant: this.state.searchSelection.length ? 'success' : 'default'
      }, "Aggiungi"))));
    }
  }, {
    key: "renderPeopleSection",
    value: function renderPeopleSection() {
      var people = this.state.people;
      return _react.default.createElement(_peopleList.default, {
        ref: this.handlePeopleListRef,
        people: people,
        onPermissionChange: this.handlePersonPermissionChange,
        onPersonRemove: this.handlePersonRemove,
        peopleToRemove: this.state.peopleToRemove
      });
    }
  }, {
    key: "render",
    value: function render() {
      return _react.default.createElement(_Modal.default, {
        applicationElement: this.applicationElement,
        open: this.props.isOpen,
        onDismiss: this.handleDismiss,
        size: "medium",
        label: "Condivisione",
        shouldCloseOnDocumentClick: true
      }, _react.default.createElement(_Modal.ModalHeader, null, _react.default.createElement(_Heading.default, null, this.props.bank.title), _react.default.createElement(_CloseButton.default, {
        onClick: this.handleDismiss,
        placement: "end",
        offset: "medium",
        variant: "icon"
      }, "Chiudi")), _react.default.createElement(_Modal.ModalBody, null, this.renderSearchSection(), _react.default.createElement("div", {
        className: styles.separator
      }), this.state.people.size > 0 ? this.renderPeopleSection() : _react.default.createElement(_Spinner.default, null)), _react.default.createElement(_Modal.ModalFooter, null, _react.default.createElement(_Button.default, {
        "data-automation": "sdk-shared-bank-cancel-button",
        variant: "light",
        onClick: this.handleDismiss,
        margin: "0 x-small 0 0"
      }, "Annulla"), _react.default.createElement(_Button.default, {
        "data-automation": "sdk-shared-bank-done-button",
        variant: "primary",
        onClick: this.handleSubmit,
        margin: "0 x-small 0 0"
      }, "Fatto")));
    }
  }]);
  SharingModalPresenter.displayName = "SharingModalPresenter";
  return SharingModalPresenter;
}(_react.Component), _class2.propTypes = {
  appContainer: _CustomPropTypes.default.selectors.isRequired,
  isOpen: _propTypes.default.bool,
  modalTrigger: _propTypes.default.node,
  // html or react element that triggered this Modal
  bank: _reactImmutableProptypes.default.record.isRequired,
  getUserInfo: _propTypes.default.func.isRequired,
  getSharedBanks: _propTypes.default.func.isRequired,
  minChars: _propTypes.default.number,
  getBank: _propTypes.default.func.isRequired,
  onShare: _propTypes.default.func,
  removeSharedBank: _propTypes.default.func.isRequired,
  search: _propTypes.default.func.isRequired,
  sharedBanks: _reactImmutableProptypes.default.list,
  updateSharedBankPermission: _propTypes.default.func.isRequired,
  shareBank: _propTypes.default.func.isRequired,
  onDismiss: _propTypes.default.func
}, _class2.defaultProps = {
  bank: null,
  isOpen: false,
  minChars: void 0,
  modalTrigger: null,
  onDismiss: noop,
  onShare: function onShare() {},
  sharedBanks: (0, _immutable.List)()
}, _temp)) || _class);
exports.default = SharingModalPresenter;