'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactIntl = require('react-intl');

var _cspaceInput = require('cspace-input');

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _pickBy = require('lodash/pickBy');

var _pickBy2 = _interopRequireDefault(_pickBy);

var _configHelpers = require('../../helpers/configHelpers');

var _permissionHelpers = require('../../helpers/permissionHelpers');

var _RecordBrowserNavBar = require('../../../styles/cspace-ui/RecordBrowserNavBar.css');

var _RecordBrowserNavBar2 = _interopRequireDefault(_RecordBrowserNavBar);

var _RecordBrowserNavItem = require('../../../styles/cspace-ui/RecordBrowserNavItem.css');

var _RecordBrowserNavItem2 = _interopRequireDefault(_RecordBrowserNavItem);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var RecordTypeInput = _cspaceInput.components.RecordTypeInput;


var messages = (0, _reactIntl.defineMessages)({
  new: {
    'id': 'recordBrowserNavBar.new',
    'defaultMessage': 'New Record'
  },
  primary: {
    'id': 'recordBrowserNavBar.primary',
    'defaultMessage': 'Primary Record'
  },
  related: {
    'id': 'recordBrowserNavBar.related',
    'defaultMessage': '+ Related'
  },
  moreRelated: {
    'id': 'recordBrowserNavBar.moreRelated',
    'defaultMessage': '+ Related'
  }
});

var filterRecordTypes = function filterRecordTypes(recordTypes, relatedRecordBrowsers, perms) {
  var existingBrowsers = relatedRecordBrowsers.toOrderedSet();

  return (0, _pickBy2.default)(recordTypes, function (recordTypeConfig, name) {
    var serviceType = (0, _get2.default)(recordTypeConfig, ['serviceConfig', 'serviceType']);

    return (serviceType === 'procedure' || serviceType === 'object') && !existingBrowsers.includes(name) && (0, _permissionHelpers.canList)(name, perms);
  });
};

var propTypes = {
  config: _propTypes2.default.object,
  csid: _propTypes2.default.string,
  recordType: _propTypes2.default.string,
  relatedRecordType: _propTypes2.default.string,
  intl: _reactIntl.intlShape,
  items: _propTypes2.default.instanceOf(_immutable2.default.List),
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  setItems: _propTypes2.default.func,
  onSelect: _propTypes2.default.func
};

var defaultProps = {
  items: _immutable2.default.List()
};

var RecordBrowserNavBar = function (_Component) {
  _inherits(RecordBrowserNavBar, _Component);

  function RecordBrowserNavBar() {
    _classCallCheck(this, RecordBrowserNavBar);

    var _this = _possibleConstructorReturn(this, (RecordBrowserNavBar.__proto__ || Object.getPrototypeOf(RecordBrowserNavBar)).call(this));

    _this.formatRecordTypeLabel = _this.formatRecordTypeLabel.bind(_this);
    _this.handleItemButtonClick = _this.handleItemButtonClick.bind(_this);
    _this.handleItemCloseButtonClick = _this.handleItemCloseButtonClick.bind(_this);
    _this.handleRecordTypeDropdownCommit = _this.handleRecordTypeDropdownCommit.bind(_this);
    return _this;
  }

  _createClass(RecordBrowserNavBar, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.initItems();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this.initItems();
    }
  }, {
    key: 'initItems',
    value: function initItems() {
      var _props = this.props,
          recordType = _props.recordType,
          relatedRecordType = _props.relatedRecordType,
          items = _props.items,
          setItems = _props.setItems;


      if (setItems && relatedRecordType && !items.includes(relatedRecordType)) {
        // We entered a related record page via URL, but there isn't currently a tab open for that
        // record type. Open the tab.

        setItems(recordType, items.push(relatedRecordType));
      }
    }
  }, {
    key: 'formatRecordTypeLabel',
    value: function formatRecordTypeLabel(name, config) {
      var intl = this.props.intl;


      return intl.formatMessage(config.messages.record.collectionName) || name;
    }
  }, {
    key: 'handleItemButtonClick',
    value: function handleItemButtonClick(event) {
      var onSelect = this.props.onSelect;


      if (onSelect) {
        var relatedRecordType = event.target.dataset.recordtype;


        onSelect(relatedRecordType);
      }
    }
  }, {
    key: 'handleItemCloseButtonClick',
    value: function handleItemCloseButtonClick(event) {
      var _props2 = this.props,
          recordType = _props2.recordType,
          relatedRecordType = _props2.relatedRecordType,
          items = _props2.items,
          setItems = _props2.setItems,
          onSelect = _props2.onSelect;
      var closedType = event.target.dataset.recordtype;


      var itemSet = items.toOrderedSet();
      var updatedItems = itemSet.delete(closedType).toList();

      if (setItems) {
        setItems(recordType, updatedItems);
      }

      if (onSelect && closedType === relatedRecordType) {
        var index = itemSet.toList().findKey(function (value) {
          return value === closedType;
        });

        if (index > updatedItems.size - 1) {
          index = updatedItems.size - 1;
        }

        var newType = updatedItems.get(index);

        onSelect(newType);
      }
    }
  }, {
    key: 'handleRecordTypeDropdownCommit',
    value: function handleRecordTypeDropdownCommit(path, value) {
      var _props3 = this.props,
          recordType = _props3.recordType,
          items = _props3.items,
          setItems = _props3.setItems,
          onSelect = _props3.onSelect;


      if (setItems) {
        var updatedItems = items.toOrderedSet().add(value).toList();

        setItems(recordType, updatedItems);
      }

      if (onSelect) {
        onSelect(value);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props4 = this.props,
          config = _props4.config,
          csid = _props4.csid,
          intl = _props4.intl,
          items = _props4.items,
          perms = _props4.perms,
          recordType = _props4.recordType,
          relatedRecordType = _props4.relatedRecordType;


      var recordTypeConfig = (0, _get2.default)(config, ['recordTypes', recordType]);

      var showRelatedItems = csid && !(0, _configHelpers.isAuthority)(recordTypeConfig) && !(0, _configHelpers.isUtility)(recordTypeConfig);

      var primaryItem = _react2.default.createElement(
        'li',
        { className: relatedRecordType ? _RecordBrowserNavItem2.default.normal : _RecordBrowserNavItem2.default.active },
        _react2.default.createElement(
          'button',
          {
            disabled: !showRelatedItems || !relatedRecordType,
            onClick: this.handleItemButtonClick
          },
          intl.formatMessage(csid ? messages.primary : messages.new)
        )
      );

      var relatedItems = void 0;

      if (showRelatedItems) {
        relatedItems = _immutable2.default.OrderedSet(items).map(function (itemRecordType) {
          var itemRecordTypeConfig = (0, _get2.default)(config, ['recordTypes', itemRecordType]);
          var label = _this2.formatRecordTypeLabel(itemRecordType, itemRecordTypeConfig);

          var className = itemRecordType === relatedRecordType ? _RecordBrowserNavItem2.default.active : _RecordBrowserNavItem2.default.normal;

          return _react2.default.createElement(
            'li',
            { className: className, key: itemRecordType },
            _react2.default.createElement(
              'button',
              {
                'data-recordtype': itemRecordType,
                disabled: itemRecordType === relatedRecordType,
                onClick: _this2.handleItemButtonClick
              },
              label
            ),
            _react2.default.createElement('button', {
              'data-recordtype': itemRecordType,
              onClick: _this2.handleItemCloseButtonClick
            })
          );
        });
      }

      var relatedRecordTypeSelector = void 0;

      if (showRelatedItems) {
        var filteredRecordTypes = filterRecordTypes(config.recordTypes, items, perms);

        if (Object.keys(filteredRecordTypes).length > 0) {
          var placeholder = items.size > 0 ? intl.formatMessage(messages.moreRelated) : intl.formatMessage(messages.related);

          relatedRecordTypeSelector = _react2.default.createElement(
            'li',
            { className: _RecordBrowserNavItem2.default.selector },
            _react2.default.createElement(RecordTypeInput, {
              filtering: false,
              indentItems: false,
              placeholder: placeholder,
              recordTypes: filteredRecordTypes,
              value: '0',
              formatRecordTypeLabel: this.formatRecordTypeLabel,
              onCommit: this.handleRecordTypeDropdownCommit
            })
          );
        }
      }

      var serviceType = (0, _get2.default)(config, ['recordTypes', recordType, 'serviceConfig', 'serviceType']);

      return _react2.default.createElement(
        'nav',
        { className: _RecordBrowserNavBar2.default[serviceType] },
        _react2.default.createElement(
          'ul',
          null,
          primaryItem,
          relatedItems,
          relatedRecordTypeSelector
        )
      );
    }
  }]);

  return RecordBrowserNavBar;
}(_react.Component);

RecordBrowserNavBar.propTypes = propTypes;
RecordBrowserNavBar.defaultProps = defaultProps;

exports.default = (0, _reactIntl.injectIntl)(RecordBrowserNavBar);