'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 _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

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

var _get2 = _interopRequireDefault(_get);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

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

var _RecordEditorContainer2 = _interopRequireDefault(_RecordEditorContainer);

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

var _SearchPanelContainer2 = _interopRequireDefault(_SearchPanelContainer);

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

var _AdminTabButtonBar = require('../admin/AdminTabButtonBar');

var _AdminTabButtonBar2 = _interopRequireDefault(_AdminTabButtonBar);

var _AccountSearchBar = require('../admin/AccountSearchBar');

var _AccountSearchBar2 = _interopRequireDefault(_AccountSearchBar);

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

var _AdminTab2 = _interopRequireDefault(_AdminTab);

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

/* global window */

const propTypes = {
  history: _propTypes2.default.object,
  location: _propTypes2.default.object,
  match: _propTypes2.default.object,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  filterDelay: _propTypes2.default.number,
  setAdminTab: _propTypes2.default.func
};

const defaultProps = {
  filterDelay: 500
};

const contextTypes = {
  config: _propTypes2.default.object.isRequired
};

const recordType = 'account';

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

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

    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.handleSearchDescriptorChange = this.handleSearchDescriptorChange.bind(this);
    this.handleSearchBarChange = this.handleSearchBarChange.bind(this);
    this.renderSearchBar = this.renderSearchBar.bind(this);

    this.state = {
      searchDescriptor: getSearchDescriptor()
    };
  }

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


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

  cloneRecord() {
    var _props = this.props;
    const history = _props.history,
          match = _props.match;
    const csid = match.params.csid;


    const query = {
      clone: csid
    };

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

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

  filter(value) {
    const searchDescriptor = this.state.searchDescriptor;


    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;


    history.replace(`/admin/${recordType}/new`);
  }

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

      this.filterTimer = null;
    }

    if (value) {
      const filterDelay = this.props.filterDelay;


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

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


    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;


      history.replace(`/admin/${recordType}/${newRecordCsid}`);
    }
  }

  handleRecordDeleted() {
    const history = this.props.history;


    history.replace(`/admin/${recordType}`);

    const searchDescriptor = this.state.searchDescriptor;


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

  handleRecordSaved() {
    const searchDescriptor = this.state.searchDescriptor;


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

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

  renderSearchBar() {
    const searchDescriptor = this.state.searchDescriptor;


    const filterValue = searchDescriptor.getIn(['searchQuery', 'sn']);

    return _react2.default.createElement(_AccountSearchBar2.default, { value: filterValue, onChange: this.handleSearchBarChange });
  }

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


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

    const normalizedCsid = csid === 'new' ? '' : csid;
    const cloneCsid = query.clone;
    const recordTypeConfig = (0, _get2.default)(config, ['recordTypes', recordType]);

    const filterValue = searchDescriptor.getIn(['searchQuery', 'sn']);
    const title = _react2.default.createElement(_reactIntl.FormattedMessage, recordTypeConfig.messages.record.collectionName);

    let recordEditor;

    if (typeof normalizedCsid !== 'undefined' && normalizedCsid !== null) {
      recordEditor = _react2.default.createElement(_RecordEditorContainer2.default, {
        cloneCsid: cloneCsid,
        config: config,
        csid: normalizedCsid,
        recordType: recordType,
        isHardDelete: true,
        onRecordCreated: this.handleRecordCreated,
        onRecordDeleted: this.handleRecordDeleted,
        onRecordSaved: this.handleRecordSaved,
        clone: this.cloneRecord
      });
    }

    return _react2.default.createElement(
      'div',
      { className: _AdminTab2.default.common },
      _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(_AdminTabButtonBar2.default, {
          isCreatable: (0, _permissionHelpers.canCreate)(recordType, perms),
          onCreateButtonClick: this.handleCreateButtonClick
        }),
        _react2.default.createElement(_SearchPanelContainer2.default, {
          config: config,
          history: history,
          isFiltered: !!filterValue,
          linkItems: false,
          listType: 'account',
          name: 'accountPage',
          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;