"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 _qs = _interopRequireDefault(require("qs"));

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

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

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

var _AdminTabButtonBar = _interopRequireDefault(require("../admin/AdminTabButtonBar"));

var _AccountSearchBar = _interopRequireDefault(require("../admin/AccountSearchBar"));

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 () { 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 = {
  history: _propTypes.default.shape({
    replace: _propTypes.default.func
  }),
  location: _propTypes.default.shape({
    search: _propTypes.default.string
  }),
  match: _propTypes.default.shape({
    params: _propTypes.default.object
  }),
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  filterDelay: _propTypes.default.number,
  userId: _propTypes.default.string,
  setAdminTab: _propTypes.default.func
};
const defaultProps = {
  filterDelay: 500
};
const contextTypes = {
  config: _propTypes.default.shape({
    recordTypes: _propTypes.default.object
  }).isRequired
};
const recordType = 'account';

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

class AccountPage extends _react.Component {
  constructor() {
    super();
    this.checkRecordDeletable = this.checkRecordDeletable.bind(this);
    this.cloneRecord = this.cloneRecord.bind(this);
    this.handleCreateButtonClick = this.handleCreateButtonClick.bind(this);
    this.handleItemClick = this.handleItemClick.bind(this);
    this.handleRecordCreated = this.handleRecordCreated.bind(this);
    this.handleRecordDeleted = this.handleRecordDeleted.bind(this);
    this.handleRecordSaved = this.handleRecordSaved.bind(this);
    this.handleSearchBarChange = this.handleSearchBarChange.bind(this);
    this.handleSearchDescriptorChange = this.handleSearchDescriptorChange.bind(this);
    this.renderSearchBar = this.renderSearchBar.bind(this);
    this.state = {
      searchDescriptor: getSearchDescriptor()
    };
  }

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

    if (setAdminTab) {
      setAdminTab(recordType);
    }
  }

  checkRecordDeletable(data) {
    const {
      userId
    } = this.props;
    const recordUserId = data.getIn(['ns2:accounts_common', 'userId']);
    return userId !== recordUserId;
  }

  cloneRecord() {
    const {
      history,
      match
    } = this.props;
    const {
      csid
    } = match.params;
    const query = {
      clone: csid
    };

    const queryString = _qs.default.stringify(query);

    history.replace({
      pathname: `/admin/${recordType}/new`,
      search: `?${queryString}`
    });
  }

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

    if (value) {
      updatedSearchQuery = searchQuery.set('sn', value);
    } else {
      updatedSearchQuery = searchQuery.delete('sn');
    }

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

  handleCreateButtonClick() {
    const {
      history
    } = this.props;
    history.replace(`/admin/${recordType}/new`);
  }

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

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


    return false;
  }

  handleRecordCreated(newRecordCsid, isNavigating) {
    if (!isNavigating) {
      const {
        history
      } = this.props;
      history.replace(`/admin/${recordType}/${newRecordCsid}`);
    }
  }

  handleRecordDeleted() {
    const {
      history
    } = this.props;
    history.replace(`/admin/${recordType}`);
    const {
      searchDescriptor
    } = this.state;
    this.setState({
      searchDescriptor: searchDescriptor.set('seqId', new Date().toISOString())
    });
  }

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

  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 {
      searchDescriptor
    } = this.state;
    const filterValue = searchDescriptor.getIn(['searchQuery', 'sn']);
    return /*#__PURE__*/_react.default.createElement(_AccountSearchBar.default, {
      value: filterValue,
      onChange: this.handleSearchBarChange
    });
  }

  render() {
    const {
      config
    } = this.context;
    const {
      history,
      location,
      match,
      perms
    } = this.props;
    const {
      searchDescriptor
    } = this.state;
    const {
      csid
    } = match.params;

    const query = _qs.default.parse(location.search.substring(1));

    const normalizedCsid = csid === 'new' ? '' : csid;
    const cloneCsid = query.clone;
    const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);
    const filterValue = searchDescriptor.getIn(['searchQuery', 'sn']);

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

    let recordEditor;

    if (typeof normalizedCsid !== 'undefined' && normalizedCsid !== null) {
      recordEditor = /*#__PURE__*/_react.default.createElement(_RecordEditorContainer.default, {
        cloneCsid: cloneCsid,
        config: config,
        csid: normalizedCsid,
        recordType: recordType,
        isHardDelete: true,
        onRecordCreated: this.handleRecordCreated,
        onRecordDeleted: this.handleRecordDeleted,
        onRecordSaved: this.handleRecordSaved,
        checkDeletable: this.checkRecordDeletable,
        clone: this.cloneRecord
      });
    }

    return /*#__PURE__*/_react.default.createElement("div", {
      className: _AdminTab.default.common
    }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_AdminTabButtonBar.default, {
      isCreatable: (0, _permissionHelpers.canCreate)(recordType, perms),
      onCreateButtonClick: this.handleCreateButtonClick
    }), /*#__PURE__*/_react.default.createElement(_SearchPanelContainer.default, {
      collapsed: false,
      collapsible: false,
      config: config,
      history: history,
      isFiltered: !!filterValue,
      linkItems: false,
      listType: "account",
      name: "accountPage",
      pageSizeOptionListName: "searchResultPagePageSizes",
      searchDescriptor: searchDescriptor,
      title: title,
      recordType: recordType,
      showSearchButton: false,
      renderTableHeader: this.renderSearchBar,
      onItemClick: this.handleItemClick,
      onSearchDescriptorChange: this.handleSearchDescriptorChange
    })), recordEditor);
  }

}

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