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

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

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

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

var formatTimeRelative = function formatTimeRelative(timestamp) {
  return timestamp ? _react2.default.createElement(_reactIntl.FormattedRelative, { value: timestamp }) : null;
};

var formatUserId = function formatUserId(userId) {
  return userId ? _react2.default.createElement(_AccountLabel2.default, { userId: userId }) : '';
};

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

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

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

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

    _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
    };
    return _this;
  }

  _createClass(RecordHistory, [{
    key: 'handlePopoverBeforeClose',
    value: function handlePopoverBeforeClose() {
      this.setState({
        showHeader: true
      });
    }
  }, {
    key: 'handlePopoverBeforeOpen',
    value: function handlePopoverBeforeOpen() {
      this.setState({
        showHeader: false
      });
    }
  }, {
    key: 'renderCurrentState',
    value: function renderCurrentState() {
      var _props = this.props,
          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);
      }

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

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

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

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

      return null;
    }
  }, {
    key: 'renderHistory',
    value: function renderHistory() {
      var data = this.props.data;


      var currentState = this.renderCurrentState();

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

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

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

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

      var items = [currentState, updated, created].filter(function (item) {
        return !!item;
      });

      return _react2.default.createElement(
        'ul',
        null,
        items.map(function (item) {
          return _react2.default.createElement(
            'li',
            { key: item.key },
            item
          );
        })
      );
    }
  }, {
    key: 'renderHeader',
    value: function renderHeader() {
      var showHeader = this.state.showHeader;


      return showHeader ? this.renderCurrentState() : _react2.default.createElement('br', null);
    }
  }, {
    key: 'render',
    value: function render() {
      var data = this.props.data;


      var content = void 0;

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

  return RecordHistory;
}(_react.Component);

exports.default = RecordHistory;


RecordHistory.propTypes = propTypes;