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

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; } /* global window */

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

var defaultProps = {
  filterDelay: 500
};

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

var recordType = 'account';

var getSearchDescriptor = function getSearchDescriptor() {
  return _immutable2.default.fromJS({
    recordType: recordType,
    searchQuery: {
      size: 20
    }
  });
};

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

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

    var _this = _possibleConstructorReturn(this, (AccountPage.__proto__ || Object.getPrototypeOf(AccountPage)).call(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.handleSearchDescriptorChange = _this.handleSearchDescriptorChange.bind(_this);
    _this.handleSearchBarChange = _this.handleSearchBarChange.bind(_this);
    _this.renderSearchBar = _this.renderSearchBar.bind(_this);

    _this.state = {
      searchDescriptor: getSearchDescriptor()
    };
    return _this;
  }

  _createClass(AccountPage, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var setAdminTab = this.props.setAdminTab;


      if (setAdminTab) {
        setAdminTab(recordType);
      }
    }
  }, {
    key: 'cloneRecord',
    value: function cloneRecord() {
      var _props = this.props,
          history = _props.history,
          match = _props.match;
      var csid = match.params.csid;


      var query = {
        clone: csid
      };

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

      history.replace({
        pathname: '/admin/' + recordType + '/new',
        search: '?' + queryString
      });
    }
  }, {
    key: 'filter',
    value: function filter(value) {
      var searchDescriptor = this.state.searchDescriptor;


      var searchQuery = searchDescriptor.get('searchQuery');

      var updatedSearchQuery = void 0;

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

      updatedSearchQuery = updatedSearchQuery.set('p', 0);

      this.setState({
        searchDescriptor: searchDescriptor.set('searchQuery', updatedSearchQuery)
      });
    }
  }, {
    key: 'handleCreateButtonClick',
    value: function handleCreateButtonClick() {
      var history = this.props.history;


      history.replace('/admin/' + recordType + '/new');
    }
  }, {
    key: 'handleSearchBarChange',
    value: function handleSearchBarChange(value) {
      var _this2 = this;

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

        this.filterTimer = null;
      }

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


        this.filterTimer = window.setTimeout(function () {
          _this2.filter(value);
          _this2.filterTimer = null;
        }, filterDelay);
      } else {
        this.filter(value);
      }
    }
  }, {
    key: 'handleItemClick',
    value: function handleItemClick(item) {
      var _props2 = this.props,
          history = _props2.history,
          perms = _props2.perms;


      if ((0, _permissionHelpers.canRead)(recordType, perms)) {
        var csid = item.get('csid');

        history.replace('/admin/' + recordType + '/' + csid);
      }

      // Prevent the default action.

      return false;
    }
  }, {
    key: 'handleRecordCreated',
    value: function handleRecordCreated(newRecordCsid, isNavigating) {
      if (!isNavigating) {
        var history = this.props.history;


        history.replace('/admin/' + recordType + '/' + newRecordCsid);
      }
    }
  }, {
    key: 'handleRecordDeleted',
    value: function handleRecordDeleted() {
      var history = this.props.history;


      history.replace('/admin/' + recordType);
    }
  }, {
    key: 'handleSearchDescriptorChange',
    value: function handleSearchDescriptorChange(searchDescriptor) {
      this.setState({
        searchDescriptor: searchDescriptor
      });
    }
  }, {
    key: 'renderSearchBar',
    value: function renderSearchBar() {
      var searchDescriptor = this.state.searchDescriptor;


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

      return _react2.default.createElement(_AccountSearchBar2.default, { value: filterValue, onChange: this.handleSearchBarChange });
    }
  }, {
    key: 'render',
    value: function render() {
      var config = this.context.config;
      var _props3 = this.props,
          history = _props3.history,
          location = _props3.location,
          match = _props3.match,
          perms = _props3.perms;
      var searchDescriptor = this.state.searchDescriptor;
      var csid = match.params.csid;


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

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

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

      var recordEditor = void 0;

      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,
          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
      );
    }
  }]);

  return AccountPage;
}(_react.Component);

exports.default = AccountPage;


AccountPage.propTypes = propTypes;
AccountPage.defaultProps = defaultProps;
AccountPage.contextTypes = contextTypes;