"use strict";

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

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

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

var _immutable = _interopRequireDefault(require("immutable"));

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

var _get = _interopRequireDefault(require("lodash/get"));

var _searchOperators = require("../../constants/searchOperators");

var _VocabularyUsedByPanelContainer = _interopRequireDefault(require("../../containers/admin/VocabularyUsedByPanelContainer"));

var _RecordEditorContainer = _interopRequireDefault(require("../../containers/record/RecordEditorContainer"));

var _SearchPanelContainer = _interopRequireDefault(require("../../containers/search/SearchPanelContainer"));

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

var _VocabularySearchBar = _interopRequireDefault(require("../admin/VocabularySearchBar"));

var _AdminTab = _interopRequireDefault(require("../../../styles/cspace-ui/AdminTab.css"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

/* global window */
const propTypes = {
  data: _propTypes.default.instanceOf(_immutable.default.Map),
  history: _propTypes.default.object,
  match: _propTypes.default.object,
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  filterDelay: _propTypes.default.number,
  readVocabularyItemRefs: _propTypes.default.func,
  setToolTab: _propTypes.default.func
};
const defaultProps = {
  filterDelay: 500
};
const contextTypes = {
  config: _propTypes.default.object.isRequired
};
const recordType = 'vocabulary';

const getSearchDescriptor = () => _immutable.default.fromJS({
  recordType,
  searchQuery: {
    size: 20,
    sort: 'displayName'
  }
});

class VocabularyPage extends _react.Component {
  constructor() {
    super();
    this.handleItemClick = this.handleItemClick.bind(this);
    this.handleRecordReadComplete = this.handleRecordReadComplete.bind(this);
    this.handleRecordSaved = this.handleRecordSaved.bind(this);
    this.handleSearchDescriptorChange = this.handleSearchDescriptorChange.bind(this);
    this.handleSearchBarChange = this.handleSearchBarChange.bind(this);
    this.renderSearchBar = this.renderSearchBar.bind(this);
    this.state = {
      searchDescriptor: getSearchDescriptor()
    };
  }

  componentDidMount() {
    const {
      setToolTab
    } = this.props;

    if (setToolTab) {
      setToolTab(recordType);
    }
  }

  filter(value) {
    const {
      searchDescriptor
    } = this.state;
    const searchQuery = searchDescriptor.get('searchQuery');
    let updatedSearchQuery;

    if (value) {
      updatedSearchQuery = searchQuery.set('as', _immutable.default.Map({
        value,
        op: _searchOperators.OP_CONTAIN,
        path: 'ns2:vocabularies_common/displayName'
      }));
    } else {
      updatedSearchQuery = searchQuery.delete('as');
    }

    updatedSearchQuery = updatedSearchQuery.set('p', 0);
    this.setState({
      filterValue: value,
      searchDescriptor: searchDescriptor.set('searchQuery', updatedSearchQuery)
    });
  }

  readItemRefs() {
    const {
      data,
      readVocabularyItemRefs
    } = this.props;

    if (readVocabularyItemRefs && data) {
      const csid = data.getIn(['document', 'ns2:vocabularies_common', 'csid']);
      const vocabularyName = data.getIn(['document', 'ns2:vocabularies_common', 'shortIdentifier']);

      if (csid && vocabularyName) {
        readVocabularyItemRefs(csid, vocabularyName);
      }
    }
  }

  handleItemClick(item) {
    const {
      history,
      perms
    } = this.props;

    if ((0, _permissionHelpers.canRead)(recordType, perms)) {
      const csid = item.get('csid');
      history.replace("/tool/".concat(recordType, "/").concat(csid));
    } // Prevent the default action.


    return false;
  }

  handleRecordReadComplete() {
    this.readItemRefs();
  }

  handleRecordSaved() {
    const {
      searchDescriptor
    } = this.state;
    this.setState({
      searchDescriptor: searchDescriptor.set('seqId', new Date().toISOString())
    });
    this.readItemRefs();
  }

  handleSearchBarChange(value) {
    if (this.filterTimer) {
      window.clearTimeout(this.filterTimer);
      this.filterTimer = null;
    }

    if (value) {
      const {
        filterDelay
      } = this.props;
      this.filterTimer = window.setTimeout(() => {
        this.filter(value);
        this.filterTimer = null;
      }, filterDelay);
    } else {
      this.filter(value);
    }
  }

  handleSearchDescriptorChange(searchDescriptor) {
    this.setState({
      searchDescriptor
    });
  }

  renderSearchBar() {
    const {
      filterValue
    } = this.state;
    return _react.default.createElement(_VocabularySearchBar.default, {
      value: filterValue,
      onChange: this.handleSearchBarChange
    });
  }

  render() {
    const {
      config
    } = this.context;
    const {
      history,
      match,
      perms
    } = this.props;
    const {
      filterValue,
      searchDescriptor
    } = this.state;
    const {
      csid
    } = match.params;
    const normalizedCsid = csid === 'new' ? '' : csid;
    const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);

    const title = _react.default.createElement(_reactIntl.FormattedMessage, recordTypeConfig.messages.record.collectionName);

    let recordEditor;
    let usedBy;

    if (typeof normalizedCsid !== 'undefined' && normalizedCsid !== null) {
      // Don't allow creating or deleting.
      let restrictedPerms = perms;
      restrictedPerms = (0, _permissionHelpers.disallowCreate)(recordType, restrictedPerms);
      restrictedPerms = (0, _permissionHelpers.disallowDelete)(recordType, restrictedPerms);
      restrictedPerms = (0, _permissionHelpers.disallowSoftDelete)(recordType, restrictedPerms);
      recordEditor = _react.default.createElement(_RecordEditorContainer.default, {
        config: config,
        csid: normalizedCsid,
        recordType: recordType,
        perms: restrictedPerms,
        onRecordReadComplete: this.handleRecordReadComplete,
        onRecordSaved: this.handleRecordSaved
      });

      if (normalizedCsid) {
        usedBy = _react.default.createElement(_VocabularyUsedByPanelContainer.default, {
          config: config,
          csid: normalizedCsid
        });
      }
    }

    return _react.default.createElement("div", {
      className: _AdminTab.default.common
    }, _react.default.createElement("div", null, _react.default.createElement(_SearchPanelContainer.default, {
      collapsed: false,
      collapsible: false,
      config: config,
      history: history,
      isFiltered: !!filterValue,
      linkItems: false,
      name: "vocabularyPage",
      pageSizeOptionListName: "searchResultPagePageSizes",
      searchDescriptor: searchDescriptor,
      title: title,
      recordType: recordType,
      showSearchButton: false,
      renderTableHeader: this.renderSearchBar,
      onItemClick: this.handleItemClick,
      onSearchDescriptorChange: this.handleSearchDescriptorChange
    })), _react.default.createElement("div", null, recordEditor, usedBy));
  }

}

exports.default = VocabularyPage;
VocabularyPage.propTypes = propTypes;
VocabularyPage.defaultProps = defaultProps;
VocabularyPage.contextTypes = contextTypes;