'use strict';

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

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 _class, _temp2;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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

/*
    References
    moment.js
    jQuery Timeago plugin, http://timeago.yarp.com/, http://timeago.yarp.com/jquery.timeago.js
*/

var RelativeTime = (_temp2 = _class = function (_React$Component) {
  _inherits(RelativeTime, _React$Component);

  function RelativeTime() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, RelativeTime);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = RelativeTime.__proto__ || Object.getPrototypeOf(RelativeTime)).call.apply(_ref, [this].concat(args))), _this), _this.tokens = {
      prefixAgo: null,
      prefixFromNow: null,
      suffixAgo: 'ago',
      suffixFromNow: 'from now',
      inPast: 'any moment now',
      seconds: 'a few seconds',
      minute: 'a minute',
      minutes: '%d minutes',
      hour: 'an hour',
      hours: '%d hours',
      day: 'a day',
      days: '%d days',
      month: 'a month',
      months: '%d months',
      year: 'a year',
      years: '%d years',
      wordSeparator: ' ',
      numbers: []

      /* Convert string time to Date() */
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  /* Strings for time difference */


  _createClass(RelativeTime, [{
    key: 'parseTimestring',
    value: function parseTimestring(iso8601) {
      var str = iso8601.trim();
      str = str.replace(/\.\d+/, ''); // remove milliseconds
      str = str.replace(/-/, '/').replace(/-/, '/');
      str = str.replace(/T/, ' ').replace(/Z/, ' UTC');
      str = str.replace(/([+-]\d\d):?(\d\d)/, ' $1$2'); // -04:00 -> -0400
      str = str.replace(/([+-]\d\d)$/, ' $100'); // +09 -> +0900
      return new Date(str);
    }

    /* Replace %d in token with number */

  }, {
    key: 'substituteToken',
    value: function substituteToken(string, number) {
      var value = this.tokens.numbers && this.tokens.numbers[number] || number;
      return string.replace(/%d/i, value);
    }

    /* Relative time in words */

  }, {
    key: 'relativeTimeString',
    value: function relativeTimeString(date) {
      if (!(date instanceof Date)) {
        return '';
      }

      var delta = Date.now() - date.getTime();

      var prefix = this.tokens.prefixAgo;
      var suffix = this.tokens.suffixAgo;

      /* Future */
      if (delta < 0) {
        prefix = this.tokens.prefixFromNow;
        suffix = this.tokens.suffixFromNow;
      }

      var seconds = Math.abs(delta) / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      var words = void 0;

      if (seconds < 45) {
        words = this.substituteToken(this.tokens.seconds, Math.round(seconds));
      } else if (seconds < 90) {
        words = this.substituteToken(this.tokens.minute, 1);
      } else if (minutes < 45) {
        words = this.substituteToken(this.tokens.minutes, Math.round(minutes));
      } else if (minutes < 90) {
        words = this.substituteToken(this.tokens.hour, 1);
      } else if (hours < 22) {
        words = this.substituteToken(this.tokens.hours, Math.round(hours));
      } else if (hours < 35) {
        words = this.substituteToken(this.tokens.day, 1);
      } else if (days < 25) {
        words = this.substituteToken(this.tokens.days, Math.round(days));
      } else if (days < 45) {
        words = this.substituteToken(this.tokens.month, 1);
      } else if (days < 365) {
        words = this.substituteToken(this.tokens.months, Math.round(days / 30));
      } else if (years < 1.5) {
        words = this.substituteToken(this.tokens.year, 1);
      } else {
        words = this.substituteToken(this.tokens.years, Math.round(years));
      }

      return [prefix, words, suffix].join(this.tokens.wordSeparator).trim();
    }

    /* Generate time string in specifier pattern */

  }, {
    key: 'format',
    value: function format(date, pattern) {
      if (!(date instanceof Date)) {
        return '';
      }

      if (pattern.toLowerCase() === 'iso8601') {
        return date.toISOString();
      }

      var patterns = {
        M: date.getMonth() + 1,
        D: date.getDate(),
        H: date.getHours(),
        m: date.getMinutes(),
        s: date.getSeconds()
      };

      // replace M, D, H, m, s
      pattern = pattern.replace(/(M+|D+|H+|m+|s+)/g, function (test) {
        var key = test.slice(-1);
        return ((test.length > 1 ? '0' : '') + patterns[key]).slice(-2);
      });

      // replace Y
      return pattern.replace(/(Y+)/g, function (test) {
        return date.getFullYear().toString().slice(-test.length);
      });
    }

    /* Display */

  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          value = _props.value,
          titleFormat = _props.titleFormat,
          props = _objectWithoutProperties(_props, ['value', 'titleFormat']);

      /* Type conversion */


      var date = void 0;

      if (value instanceof Date) {
        date = value;
      } else if (typeof value === 'string') {
        date = this.parseTimestring(value);
      } else if (typeof value === 'number') {
        date = new Date(value);
      } else {
        return _react2.default.createElement(
          'span',
          null,
          'Invalid date'
        );
      }

      /* Format conversion */
      var machineReadable = this.format(date, 'iso8601'); //  ISO-8601
      var humanReadable = this.relativeTimeString(date);

      return _react2.default.createElement(
        'time',
        _extends({
          title: this.format(date, titleFormat)
        }, props, {
          dateTime: machineReadable }),
        humanReadable
      );
    }
  }]);

  return RelativeTime;
}(_react2.default.Component), _class.propTypes = {
  /* Value */
  value: _propTypes2.default.oneOfType([_propTypes2.default.instanceOf(Date), _propTypes2.default.number, _propTypes2.default.string]).isRequired,

  /* Datetime format which is used to set title attribute on dates. */
  titleFormat: _propTypes2.default.string
}, _class.defaultProps = {
  titleFormat: 'iso8601' }, _temp2);
exports.default = RelativeTime;