'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = undefined;

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec, _class, _class2, _temp2;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _immutable = require('immutable');

var _reactImmutableProptypes = require('react-immutable-proptypes');

var _reactImmutableProptypes2 = _interopRequireDefault(_reactImmutableProptypes);

var _set = require('lodash/fp/set');

var _set2 = _interopRequireDefault(_set);

var _Modal = require('@instructure/ui-overlays/lib/components/Modal');

var _Modal2 = _interopRequireDefault(_Modal);

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

var _Heading2 = _interopRequireDefault(_Heading);

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

var _Button2 = _interopRequireDefault(_Button);

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

var _CloseButton2 = _interopRequireDefault(_CloseButton);

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

var _Select2 = _interopRequireDefault(_Select);

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

var _Grid2 = _interopRequireDefault(_Grid);

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

var _lib2 = _interopRequireDefault(_lib);

var _constants = require('../../../constants');

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

var _ElementsForSelectors2 = _interopRequireDefault(_ElementsForSelectors);

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

var _CustomPropTypes2 = _interopRequireDefault(_CustomPropTypes);

var _peopleList = require('./peopleList');

var _peopleList2 = _interopRequireDefault(_peopleList);

var _asyncSearch = require('./asyncSearch');

var _asyncSearch2 = _interopRequireDefault(_asyncSearch);

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

var _Spinner2 = _interopRequireDefault(_Spinner);

var _theme = require('./theme');

var _theme2 = _interopRequireDefault(_theme);

var _formatMessage = require('../../../common/format-message');

var _formatMessage2 = _interopRequireDefault(_formatMessage);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n.SharingModal__styles__separator {\n  width: 100%;\n  margin: ' + theme.separatorMargin + ' 0;\n  padding: 0;\n  border-bottom: solid ' + theme.separatorBorderWidth + ';\n  border-color: ' + theme.separatorColor + ';\n}\n\n.SharingModal__styles__labelRemoved {\n  text-decoration: line-through;\n}\n';
  },
  'separator': 'SharingModal__styles__separator',
  'labelRemoved': 'SharingModal__styles__labelRemoved'
};


var noop = function noop() {};

var SharingModalPresenter = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(SharingModalPresenter, _Component);

  function SharingModalPresenter() {
    var _ref;

    var _temp, _this, _ret;

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

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

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = SharingModalPresenter.__proto__ || Object.getPrototypeOf(SharingModalPresenter)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      people: (0, _immutable.List)(),
      newPeople: (0, _immutable.List)(),
      searchSelection: [],
      peopleToRemove: []
    }, _this.peopleListRef = null, _this.shareButtonRef = null, _this.applicationElement = function () {
      return (0, _ElementsForSelectors2.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) {
        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, _toConsumableArray3.default)(_this.state.peopleToRemove), [id]) });
      }
    }, _this.handleSearchPermissionChange = function (_ref2) {
      var value = _ref2.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, _set2.default)('[' + index + '].permission', permission, _this.state.people)
      });
    }, _this.handlePeopleListRef = function (node) {
      _this.peopleListRef = node;
    }, _this.handleShareButtonRef = function (node) {
      _this.shareButtonRef = node;
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.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 _react2.default.createElement(
        _Grid2.default,
        { vAlign: 'bottom', colSpacing: 'small' },
        _react2.default.createElement(
          _Grid.GridRow,
          null,
          _react2.default.createElement(
            _Grid.GridCol,
            null,
            _react2.default.createElement(_asyncSearch2.default, {
              search: this.props.search,
              onSelectionChange: this.handleSearchSelectionChange,
              selectedOption: this.state.searchSelection,
              selectionFilter: this.handleSearchFilter
            })
          ),
          false && _react2.default.createElement(
            _Grid.GridCol,
            { width: 'auto' },
            _react2.default.createElement(
              _Select2.default,
              {
                onChange: this.handleSearchPermissionChange,
                value: this.state.searchPermission,
                label: 'Uru',
                disabled: true
              },
              _react2.default.createElement(
                'option',
                { value: _constants.CAN_EDIT },
                'Ka taea te whakatika'
              ),
              _react2.default.createElement(
                'option',
                { value: _constants.READ_ONLY },
                'P\u0101nui anake'
              )
            )
          ),
          _react2.default.createElement(
            _Grid.GridCol,
            { width: 'auto' },
            _react2.default.createElement(
              _Button2.default,
              {
                'data-automation': 'sdk-shared-bank-add-user-button',
                ref: this.handleShareButtonRef,
                onClick: this.handleShare,
                variant: this.state.searchSelection.length ? 'success' : 'default'
              },
              'T\u0101piri'
            )
          )
        )
      );
    }
  }, {
    key: 'renderPeopleSection',
    value: function renderPeopleSection() {
      var people = this.state.people;


      return _react2.default.createElement(_peopleList2.default, {
        ref: this.handlePeopleListRef,
        people: people,
        onPermissionChange: this.handlePersonPermissionChange,
        onPersonRemove: this.handlePersonRemove,
        peopleToRemove: this.state.peopleToRemove
      });
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Modal2.default,
        {
          applicationElement: this.applicationElement,
          open: this.props.isOpen,
          onDismiss: this.handleDismiss,
          size: 'medium',
          label: 'E tuari ana',
          shouldCloseOnDocumentClick: true
        },
        _react2.default.createElement(
          _Modal.ModalHeader,
          null,
          _react2.default.createElement(
            _Heading2.default,
            null,
            this.props.bank.title
          ),
          _react2.default.createElement(_CloseButton2.default, {
            onClick: this.handleDismiss,
            placement: 'end',
            offset: 'medium',
            variant: 'icon'
          })
        ),
        _react2.default.createElement(
          _Modal.ModalBody,
          null,
          this.renderSearchSection(),
          _react2.default.createElement('div', { className: styles.separator }),
          this.state.people.size > 0 ? this.renderPeopleSection() : _react2.default.createElement(_Spinner2.default, null)
        ),
        _react2.default.createElement(
          _Modal.ModalFooter,
          null,
          _react2.default.createElement(
            _Button2.default,
            {
              'data-automation': 'sdk-shared-bank-cancel-button',
              variant: 'light',
              onClick: this.handleDismiss,
              margin: '0 x-small 0 0'
            },
            'Whakakore'
          ),
          _react2.default.createElement(
            _Button2.default,
            {
              'data-automation': 'sdk-shared-bank-done-button',
              variant: 'primary',
              onClick: this.handleSubmit,
              margin: '0 x-small 0 0'
            },
            'Kua mahia'
          )
        )
      );
    }
  }]);
  SharingModalPresenter.displayName = 'SharingModalPresenter'
  ;
  return SharingModalPresenter;
}(_react.Component), _class2.propTypes = {
  appContainer: _CustomPropTypes2.default.selectors.isRequired,
  isOpen: _propTypes2.default.bool,
  modalTrigger: _propTypes2.default.node, // html or react element that triggered this Modal
  bank: _reactImmutableProptypes2.default.record.isRequired,
  getUserInfo: _propTypes2.default.func.isRequired,
  getSharedBanks: _propTypes2.default.func.isRequired,
  getBank: _propTypes2.default.func.isRequired,
  removeSharedBank: _propTypes2.default.func.isRequired,
  search: _propTypes2.default.func.isRequired,
  sharedBanks: _reactImmutableProptypes2.default.list,
  updateSharedBankPermission: _propTypes2.default.func.isRequired,
  shareBank: _propTypes2.default.func.isRequired,
  onDismiss: _propTypes2.default.func
}, _class2.defaultProps = {
  bank: null,
  isOpen: false,
  modalTrigger: null,
  onDismiss: noop,
  sharedBanks: (0, _immutable.List)()
}, _temp2)) || _class);
exports.default = SharingModalPresenter;