import getDayStartTime from './getDayStartTime';
import formatToDate from './formatToDate';

/**
 * 获取事件发生到现在的可读时间
 * @param {number} time 事件发生时时间戳
 * @param {{
 *   justNow: string;
 *   minutesAgo: string;
 *   hoursAgo: string;
 *   yesterday : string;
 *   future: string;
 * }} timeNames
 * @returns
 * 1分钟以内       => 刚刚
 * [1分钟,60分钟） => n分钟前（例:8分钟前）
 * [1小时,24小时） => n小时前（例: 8小时前）
 * 其他           => 年-月-日（例: 2016-08-05）
 */
function formatTime(time, timeNames) {
  var date = formatToDate(time);
  if (!date) return '';
  if (!timeNames) timeNames = {};
  var justNow = timeNames.justNow || '刚刚';
  var minutesAgo = timeNames.minutesAgo || '分钟前';
  var hoursAgo = timeNames.hoursAgo || '小时前';
  var yesterday = timeNames.yesterday || '昨天';
  var future = timeNames.future || '';
  var now = Date.now();
  time = date.valueOf();
  if (now < time) return future;
  if (now - time <= 6e4) return justNow;

  if (now - time < 36e5) {
    return Math.floor((now - time) / 6e4) + minutesAgo;
  }

  if (now - time < 864e5) {
    return Math.floor((now - time) / 36e5) + hoursAgo;
  }

  if (getDayStartTime(new Date()) - time < 864e5) {
    return yesterday;
  }

  var y = date.getFullYear();
  var m = "0".concat(date.getMonth() + 1).substr(-2);
  var d = "0".concat(date.getDate()).substr(-2);

  if (y === new Date().getFullYear()) {
    return "".concat(m, "-").concat(d);
  }

  return "".concat(y, "-").concat(m, "-").concat(d);
}

export default formatTime;
