'use strict';

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

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

const RecordTypeInput = _cspaceInput.components.RecordTypeInput;


const 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'
  }
});

const filterRecordTypes = (recordTypes, relatedRecordBrowsers, perms) => {
  const existingBrowsers = relatedRecordBrowsers.toOrderedSet();

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

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

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

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

class RecordBrowserNavBar extends _react.Component {
  constructor() {
    super();

    this.formatRecordTypeLabel = this.formatRecordTypeLabel.bind(this);
    this.handleItemButtonClick = this.handleItemButtonClick.bind(this);
    this.handleItemCloseButtonClick = this.handleItemCloseButtonClick.bind(this);
    this.handleRecordTypeDropdownCommit = this.handleRecordTypeDropdownCommit.bind(this);
  }

  componentDidMount() {
    this.initItems();
  }

  componentDidUpdate() {
    this.initItems();
  }

  initItems() {
    var _props = this.props;
    const 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));
    }
  }

  formatRecordTypeLabel(name, config) {
    const intl = this.props.intl;


    return intl.formatMessage(config.messages.record.collectionName) || name;
  }

  handleItemButtonClick(event) {
    const onSelect = this.props.onSelect;


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


      onSelect(relatedRecordType);
    }
  }

  handleItemCloseButtonClick(event) {
    var _props2 = this.props;
    const recordType = _props2.recordType,
          relatedRecordType = _props2.relatedRecordType,
          items = _props2.items,
          setItems = _props2.setItems,
          onSelect = _props2.onSelect;
    const closedType = event.target.dataset.recordtype;


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

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

    if (onSelect && closedType === relatedRecordType) {
      let index = itemSet.toList().findKey(value => value === closedType);

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

      const newType = updatedItems.get(index);

      onSelect(newType);
    }
  }

  handleRecordTypeDropdownCommit(path, value) {
    var _props3 = this.props;
    const recordType = _props3.recordType,
          items = _props3.items,
          setItems = _props3.setItems,
          onSelect = _props3.onSelect;


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

      setItems(recordType, updatedItems);
    }

    if (onSelect) {
      onSelect(value);
    }
  }

  render() {
    var _props4 = this.props;
    const config = _props4.config,
          csid = _props4.csid,
          intl = _props4.intl,
          items = _props4.items,
          perms = _props4.perms,
          recordType = _props4.recordType,
          relatedRecordType = _props4.relatedRecordType;


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

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

    const 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)
      )
    );

    let relatedItems;

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

        const 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: this.handleItemButtonClick
            },
            label
          ),
          _react2.default.createElement('button', {
            'data-recordtype': itemRecordType,
            onClick: this.handleItemCloseButtonClick
          })
        );
      });
    }

    let relatedRecordTypeSelector;

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

      if (Object.keys(filteredRecordTypes).length > 0) {
        const 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
          })
        );
      }
    }

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

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

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