import _extends from "@babel/runtime/helpers/extends";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useEffect, useRef, useReducer } from 'react';
import Statistic from './Statistic';
import { formatCountdown } from './utils';
import { cloneElement } from '../_util/reactNode';
var REFRESH_INTERVAL = 1000 / 30;

function getTime(value) {
  return new Date(value).getTime();
}

function defaultFormatter(value) {
  return value;
}

var Countdown = function Countdown(props) {
  var value = props.value,
      format = props.format,
      onFinish = props.onFinish,
      _props$formatter = props.formatter,
      formatter = _props$formatter === void 0 ? defaultFormatter : _props$formatter; // 强制渲染界面

  var _useReducer = useReducer(function (x) {
    return x + 1;
  }, 0),
      _useReducer2 = _slicedToArray(_useReducer, 2),
      forceUpdate = _useReducer2[1];

  var timeStamp = getTime(value);
  var countdownRef = useRef();
  var idRef = useRef(); // 触发渲染界面，如果达到目标位置不执行

  countdownRef.current = function () {
    forceUpdate();

    if (timeStamp <= Date.now()) {
      clearInterval(Number(idRef.current));

      if (onFinish && timeStamp < Date.now()) {
        onFinish();
      }
    }
  }; // 启动计时器


  useEffect(function () {
    if (timeStamp >= Date.now()) {
      if (!idRef.current) {
        idRef.current = setInterval(function () {
          countdownRef.current();
        }, REFRESH_INTERVAL);
      }
    } else {
      clearInterval(Number(idRef.current));
    }

    return function () {
      return clearInterval(Number(idRef.current));
    };
  }, [format, value]); // Countdown do not need display the timeStamp

  var valueRender = function valueRender(node) {
    return cloneElement(node, {
      title: undefined
    });
  };

  var countdownFormatter = function countdownFormatter(valueFormatter, config) {
    var value = formatCountdown(valueFormatter, _objectSpread(_objectSpread({}, config), {}, {
      format: format
    }));

    if (typeof formatter === 'function') {
      return formatter(value);
    }

    return value;
  };

  return /*#__PURE__*/React.createElement(Statistic, _extends({
    valueRender: valueRender
  }, props, {
    formatter: countdownFormatter
  }));
};

Countdown.defaultProps = {
  format: 'HH:mm:ss'
};
export default Countdown;
//# sourceMappingURL=Countdown.js.map
