"use strict";
"use client";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _rcUtil = require("rc-util");
var _raf = _interopRequireDefault(require("rc-util/lib/raf"));
var _reactNode = require("../_util/reactNode");
var _Statistic = _interopRequireDefault(require("./Statistic"));
var _utils = require("./utils");
var __rest = void 0 && (void 0).__rest || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};
function getTime(value) {
  return new Date(value).getTime();
}
const StatisticTimer = props => {
  const {
      value,
      format = 'HH:mm:ss',
      onChange,
      onFinish,
      type
    } = props,
    rest = __rest(props, ["value", "format", "onChange", "onFinish", "type"]);
  const down = type === 'countdown';
  // We reuse state here to do same as `forceUpdate`
  const [showTime, setShowTime] = React.useState(null);
  // ======================== Update ========================
  const update = (0, _rcUtil.useEvent)(() => {
    const now = Date.now();
    const timestamp = getTime(value);
    setShowTime({});
    const timeDiff = !down ? now - timestamp : timestamp - now;
    onChange === null || onChange === void 0 ? void 0 : onChange(timeDiff);
    // Only countdown will trigger `onFinish`
    if (down && timestamp < now) {
      onFinish === null || onFinish === void 0 ? void 0 : onFinish();
      return false;
    }
    return true;
  });
  // Effect trigger
  React.useEffect(() => {
    let rafId;
    const clear = () => _raf.default.cancel(rafId);
    const rafUpdate = () => {
      rafId = (0, _raf.default)(() => {
        if (update()) {
          rafUpdate();
        }
      });
    };
    rafUpdate();
    return clear;
  }, [value, down]);
  React.useEffect(() => {
    setShowTime({});
  }, []);
  // ======================== Format ========================
  const formatter = (formatValue, config) => showTime ? (0, _utils.formatCounter)(formatValue, Object.assign(Object.assign({}, config), {
    format
  }), down) : '-';
  const valueRender = node => (0, _reactNode.cloneElement)(node, {
    title: undefined
  });
  // ======================== Render ========================
  return /*#__PURE__*/React.createElement(_Statistic.default, Object.assign({}, rest, {
    value: value,
    valueRender: valueRender,
    formatter: formatter
  }));
};
var _default = exports.default = StatisticTimer;