'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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 _cspaceLayout = require('cspace-layout');

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

var _AccountLabel = require('../user/AccountLabel');

var _AccountLabel2 = _interopRequireDefault(_AccountLabel);

var _RecordHistory = require('../../../styles/cspace-ui/RecordHistory.css');

var _RecordHistory2 = _interopRequireDefault(_RecordHistory);

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

const messages = (0, _reactIntl.defineMessages)({
  updated: {
    'id': 'recordHistory.updated',
    'defaultMessage': '{style, select, full {Updated {date} {time} by {user}} dateTime {Updated {date} {time}}}'
  },
  created: {
    'id': 'recordHistory.created',
    'defaultMessage': '{style, select, full {Created {date} {time} by {user}} dateTime {Created {date} {time}}}'
  },
  savedRelative: {
    'id': 'recordHistory.savedRelative',
    'defaultMessage': 'Saved {relativeTime}'
  },
  editing: {
    'id': 'recordHistory.editing',
    'defaultMessage': 'Editing'
  },
  saving: {
    'id': 'recordHistory.saving',
    'defaultMessage': 'Saving'
  }
});

const formatDate = timestamp => timestamp ? _react2.default.createElement(_reactIntl.FormattedDate, { value: timestamp, day: 'numeric', month: 'short', year: 'numeric' }) : null;

const formatTime = timestamp => timestamp ? _react2.default.createElement(_reactIntl.FormattedTime, { value: timestamp, hour: 'numeric', minute: 'numeric', second: 'numeric' }) : null;

const formatTimeRelative = timestamp => timestamp ? _react2.default.createElement(_reactIntl.FormattedRelative, { value: timestamp }) : null;

const formatUserId = userId => userId ? _react2.default.createElement(_AccountLabel2.default, { userId: userId }) : '';

const propTypes = {
  data: _propTypes2.default.instanceOf(_immutable2.default.Map),
  isModified: _propTypes2.default.bool,
  isSavePending: _propTypes2.default.bool
};

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

    this.renderHistory = this.renderHistory.bind(this);
    this.handlePopoverBeforeClose = this.handlePopoverBeforeClose.bind(this);
    this.handlePopoverBeforeOpen = this.handlePopoverBeforeOpen.bind(this);

    // The header shows last saved time as a FormattedRelative that gets automatically updated at
    // most every ten seconds. The popup content also shows last saved time as a FormattedRelative,
    // but since it is mounted at a different time than the one in the header, the two can easily
    // be out of sync.

    // This is fixed by unmounting the one in the header when the popup is open, and
    // remounting it when the popup is closed, in order to force it to update to the same (or
    // greater) value as was shown in the popup.

    this.state = {
      showHeader: true
    };
  }

  handlePopoverBeforeClose() {
    this.setState({
      showHeader: true
    });
  }

  handlePopoverBeforeOpen() {
    this.setState({
      showHeader: false
    });
  }

  renderCurrentState() {
    var _props = this.props;
    const data = _props.data,
          isModified = _props.isModified,
          isSavePending = _props.isSavePending;


    if (isSavePending) {
      return _react2.default.createElement(_reactIntl.FormattedMessage, messages.saving);
    }

    if (isModified) {
      return _react2.default.createElement(_reactIntl.FormattedMessage, messages.editing);
    }

    const updatedTimestamp = (0, _recordDataHelpers.getUpdatedTimestamp)(data);

    if (updatedTimestamp) {
      return _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.savedRelative, {
        key: 'saved',
        values: {
          relativeTime: formatTimeRelative(updatedTimestamp)
        }
      }));
    }

    const createdTimestamp = (0, _recordDataHelpers.getCreatedTimestamp)(data);

    if (createdTimestamp) {
      return _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.savedRelative, {
        key: 'saved',
        values: {
          relativeTime: formatTimeRelative(createdTimestamp)
        }
      }));
    }

    return null;
  }

  renderHistory() {
    const data = this.props.data;


    const currentState = this.renderCurrentState();

    const updatedTimestamp = (0, _recordDataHelpers.getUpdatedTimestamp)(data);
    const updatedUserId = (0, _recordDataHelpers.getUpdatedUser)(data);

    let updated = null;

    if (updatedTimestamp) {
      updated = _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.updated, {
        key: 'updated',
        values: {
          date: formatDate(updatedTimestamp),
          time: formatTime(updatedTimestamp),
          user: formatUserId(updatedUserId),
          style: updatedUserId ? 'full' : 'dateTime'
        }
      }));
    }

    const createdTimestamp = (0, _recordDataHelpers.getCreatedTimestamp)(data);
    const createdUserId = (0, _recordDataHelpers.getCreatedUser)(data);

    let created = null;

    if (createdTimestamp) {
      created = _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.created, {
        key: 'created',
        values: {
          date: formatDate(createdTimestamp),
          time: formatTime(createdTimestamp),
          user: formatUserId(createdUserId),
          style: createdUserId ? 'full' : 'dateTime'
        }
      }));
    }

    const items = [currentState, updated, created].filter(item => !!item);

    return _react2.default.createElement(
      'ul',
      null,
      items.map(item => _react2.default.createElement(
        'li',
        { key: item.key },
        item
      ))
    );
  }

  renderHeader() {
    const showHeader = this.state.showHeader;


    return showHeader ? this.renderCurrentState() : _react2.default.createElement('br', null);
  }

  render() {
    const data = this.props.data;


    let content;

    if ((0, _recordDataHelpers.getUpdatedTimestamp)(data) || (0, _recordDataHelpers.getCreatedTimestamp)(data)) {
      content = _react2.default.createElement(_cspaceLayout.Popover, {
        align: 'right',
        header: this.renderHeader(),
        renderContent: this.renderHistory,
        onBeforeOpen: this.handlePopoverBeforeOpen,
        onBeforeClose: this.handlePopoverBeforeClose
      });
    } else {
      content = this.renderCurrentState();
    }

    return _react2.default.createElement(
      'div',
      { className: _RecordHistory2.default.common },
      content
    );
  }
}

exports.default = RecordHistory;
RecordHistory.propTypes = propTypes;