'use strict';

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

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

var _qs2 = _interopRequireDefault(_qs);

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

var _get2 = _interopRequireDefault(_get);

var _ErrorPage = require('./ErrorPage');

var _ErrorPage2 = _interopRequireDefault(_ErrorPage);

var _RecordTitleBarContainer = require('../../containers/record/RecordTitleBarContainer');

var _RecordTitleBarContainer2 = _interopRequireDefault(_RecordTitleBarContainer);

var _RecordBrowserContainer = require('../../containers/record/RecordBrowserContainer');

var _RecordBrowserContainer2 = _interopRequireDefault(_RecordBrowserContainer);

var _RecordSideBar = require('../record/RecordSideBar');

var _RecordSideBar2 = _interopRequireDefault(_RecordSideBar);

var _configHelpers = require('../../helpers/configHelpers');

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

var _recordDataHelpers = require('../../helpers/recordDataHelpers');

var _RecordPage = require('../../../styles/cspace-ui/RecordPage.css');

var _RecordPage2 = _interopRequireDefault(_RecordPage);

var _PageBody = require('../../../styles/cspace-ui/PageBody.css');

var _PageBody2 = _interopRequireDefault(_PageBody);

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

var getParams = exports.getParams = function getParams(props) {
  var config = props.config;
  var _props$match$params = props.match.params,
      recordType = _props$match$params.recordType,
      path1 = _props$match$params.path1,
      path2 = _props$match$params.path2,
      path3 = _props$match$params.path3;


  var vocabulary = void 0;
  var csid = void 0;
  var relatedRecordType = void 0;
  var relatedCsid = void 0;

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

  if (recordTypeConfig) {
    var serviceType = (0, _get2.default)(recordTypeConfig, ['serviceConfig', 'serviceType']);

    if (serviceType === 'authority') {
      vocabulary = path1;
      csid = path2;
      relatedRecordType = path3;
    } else {
      csid = path1;
      relatedRecordType = path2;
      relatedCsid = path3;
    }
  }

  return {
    recordType: recordType,
    vocabulary: vocabulary,
    csid: csid,
    relatedRecordType: relatedRecordType,
    relatedCsid: relatedCsid
  };
};

var propTypes = {
  config: _propTypes2.default.object.isRequired,
  data: _propTypes2.default.instanceOf(_immutable2.default.Map),
  error: _propTypes2.default.instanceOf(_immutable2.default.Map),
  history: _propTypes2.default.object,
  location: _propTypes2.default.object,
  // Use of the match prop isn't being detected by eslint.
  match: _propTypes2.default.object, // eslint-disable-line react/no-unused-prop-types
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  readRecord: _propTypes2.default.func
};

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

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

    var _this = _possibleConstructorReturn(this, (RecordPage.__proto__ || Object.getPrototypeOf(RecordPage)).call(this));

    _this.handleShowRelated = _this.handleShowRelated.bind(_this);
    _this.handleTitleBarDocked = _this.handleTitleBarDocked.bind(_this);

    _this.state = {
      headerDockPosition: null
    };
    return _this;
  }

  _createClass(RecordPage, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.initRecord();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var params = getParams(this.props);
      var prevParams = getParams(prevProps);

      var csid = params.csid;
      var prevCsid = prevParams.csid;
      var perms = this.props.perms;
      var prevPerms = prevProps.perms;


      if (csid !== prevCsid || perms !== prevPerms) {
        this.initRecord();
      }
    }
  }, {
    key: 'initRecord',
    value: function initRecord() {
      var _props = this.props,
          config = _props.config,
          readRecord = _props.readRecord;

      var _getParams = getParams(this.props),
          recordType = _getParams.recordType,
          vocabulary = _getParams.vocabulary,
          csid = _getParams.csid;

      var normalizedCsid = csid === 'new' ? '' : csid;

      if (normalizedCsid && readRecord) {
        var recordTypeConfig = (0, _get2.default)(config, ['recordTypes', recordType]);

        var vocabularyConfig = vocabulary ? (0, _get2.default)(recordTypeConfig, ['vocabularies', vocabulary]) : undefined;

        readRecord(config, recordTypeConfig, vocabularyConfig, normalizedCsid);
      }
    }
  }, {
    key: 'handleShowRelated',
    value: function handleShowRelated(relatedRecordType, relatedCsid) {
      var _getParams2 = getParams(this.props),
          recordType = _getParams2.recordType,
          vocabulary = _getParams2.vocabulary,
          csid = _getParams2.csid;

      var _props2 = this.props,
          history = _props2.history,
          location = _props2.location;


      var path = [recordType, vocabulary, csid, relatedRecordType, relatedCsid].filter(function (part) {
        return !!part;
      }).join('/');

      history.replace({
        pathname: '/record/' + path,
        state: location.state
      });
    }
  }, {
    key: 'handleTitleBarDocked',
    value: function handleTitleBarDocked(height) {
      this.setState({
        headerDockPosition: height
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var headerDockPosition = this.state.headerDockPosition;
      var _props3 = this.props,
          config = _props3.config,
          data = _props3.data,
          error = _props3.error,
          history = _props3.history,
          location = _props3.location,
          perms = _props3.perms;


      if (error) {
        return _react2.default.createElement(_ErrorPage2.default, { error: error.toJS() });
      }

      var _getParams3 = getParams(this.props),
          recordType = _getParams3.recordType,
          vocabulary = _getParams3.vocabulary,
          csid = _getParams3.csid,
          relatedRecordType = _getParams3.relatedRecordType,
          relatedCsid = _getParams3.relatedCsid;

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

      var cloneCsid = query.clone;
      var normalizedCsid = csid === 'new' ? '' : csid || '';
      var normalizedRelatedCsid = relatedCsid === 'new' ? '' : relatedCsid;

      var validation = (0, _configHelpers.validateLocation)(config, {
        recordType: recordType,
        vocabulary: vocabulary,
        relatedRecordType: relatedRecordType,
        csid: normalizedCsid,
        relatedCsid: normalizedRelatedCsid
      });

      if (validation.error) {
        return _react2.default.createElement(_ErrorPage2.default, { error: validation.error });
      }

      var locationState = location.state;

      var searchName = void 0;
      var searchDescriptor = void 0;

      if (locationState) {
        searchName = locationState.searchName;
        searchDescriptor = _immutable2.default.fromJS(locationState.searchDescriptor);
      }

      var serviceType = (0, _get2.default)(config, ['recordTypes', recordType, 'serviceConfig', 'serviceType']);
      var workflowState = (0, _recordDataHelpers.getWorkflowState)(data);

      var isRelatable = workflowState !== 'locked' && (0, _permissionHelpers.canRelate)(recordType, perms);

      return _react2.default.createElement(
        'div',
        { className: _RecordPage2.default[serviceType] },
        _react2.default.createElement(_RecordTitleBarContainer2.default, {
          csid: normalizedCsid,
          recordType: recordType,
          vocabulary: vocabulary,
          searchName: searchName,
          searchDescriptor: searchDescriptor,
          updateDocumentTitle: true,
          onDocked: this.handleTitleBarDocked
        }),
        _react2.default.createElement(
          'div',
          { className: _PageBody2.default.common },
          _react2.default.createElement(_RecordBrowserContainer2.default, {
            cloneCsid: cloneCsid,
            csid: normalizedCsid,
            dockTop: headerDockPosition,
            history: history,
            location: location,
            workflowState: workflowState,
            recordType: recordType,
            relatedCsid: normalizedRelatedCsid,
            relatedRecordType: relatedRecordType,
            vocabulary: vocabulary,
            config: config,
            onShowRelated: this.handleShowRelated
          }),
          _react2.default.createElement(_RecordSideBar2.default, {
            csid: normalizedCsid,
            recordType: recordType,
            vocabulary: vocabulary,
            config: config,
            history: history,
            isRelatable: isRelatable
          })
        )
      );
    }
  }]);

  return RecordPage;
}(_react.Component);

exports.default = RecordPage;


RecordPage.propTypes = propTypes;