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

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

var _AccountLabel = _interopRequireDefault(require("../user/AccountLabel"));

var _RecordHistory = _interopRequireDefault(require("../../../styles/cspace-ui/RecordHistory.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; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

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 ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedDate, {
  value: timestamp,
  day: "numeric",
  month: "short",
  year: "numeric"
}) : null;

const formatTime = timestamp => timestamp ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedTime, {
  value: timestamp,
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
}) : null;

const formatTimeRelative = timestamp => timestamp ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedRelative, {
  value: timestamp
}) : null;

const formatUserId = userId => userId ? /*#__PURE__*/_react.default.createElement(_AccountLabel.default, {
  userId: userId
}) : '';

const propTypes = {
  data: _propTypes.default.instanceOf(_immutable.default.Map),
  isModified: _propTypes.default.bool,
  isSavePending: _propTypes.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() {
    const {
      data,
      isModified,
      isSavePending
    } = this.props;

    if (isSavePending) {
      return /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.saving);
    }

    if (isModified) {
      return /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.editing);
    }

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

    if (updatedTimestamp) {
      return /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.savedRelative, {
        key: "saved",
        values: {
          relativeTime: formatTimeRelative(updatedTimestamp)
        }
      }));
    }

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

    if (createdTimestamp) {
      return /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.savedRelative, {
        key: "saved",
        values: {
          relativeTime: formatTimeRelative(createdTimestamp)
        }
      }));
    }

    return null;
  }

  renderHistory() {
    const {
      data
    } = this.props;
    const currentState = this.renderCurrentState();
    const updatedTimestamp = (0, _recordDataHelpers.getUpdatedTimestamp)(data);
    const updatedUserId = (0, _recordDataHelpers.getUpdatedUser)(data);
    let updated = null;

    if (updatedTimestamp) {
      updated = /*#__PURE__*/_react.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 = /*#__PURE__*/_react.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 /*#__PURE__*/_react.default.createElement("ul", null, items.map(item => /*#__PURE__*/_react.default.createElement("li", {
      key: item.key
    }, item)));
  }

  renderHeader() {
    const {
      showHeader
    } = this.state;
    return showHeader ? this.renderCurrentState() : /*#__PURE__*/_react.default.createElement("br", null);
  }

  render() {
    const {
      data
    } = this.props;
    let content;

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

    return /*#__PURE__*/_react.default.createElement("div", {
      className: _RecordHistory.default.common
    }, content);
  }

}

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