import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useState, useCallback } from 'react';
import { Time } from './utils';
import { useInterval } from './hooks';
export default function useStopwatch() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
    autoStart = _ref.autoStart,
    offsetTimestamp = _ref.offsetTimestamp;
  var _useState = useState(Time.getSecondsFromExpiry(offsetTimestamp, true) || 0),
    _useState2 = _slicedToArray(_useState, 2),
    passedSeconds = _useState2[0],
    setPassedSeconds = _useState2[1];
  var _useState3 = useState(new Date()),
    _useState4 = _slicedToArray(_useState3, 2),
    prevTime = _useState4[0],
    setPrevTime = _useState4[1];
  var _useState5 = useState(passedSeconds + Time.getSecondsFromPrevTime(prevTime || 0, true)),
    _useState6 = _slicedToArray(_useState5, 2),
    seconds = _useState6[0],
    setSeconds = _useState6[1];
  var _useState7 = useState(autoStart),
    _useState8 = _slicedToArray(_useState7, 2),
    isRunning = _useState8[0],
    setIsRunning = _useState8[1];
  useInterval(function () {
    setSeconds(passedSeconds + Time.getSecondsFromPrevTime(prevTime, true));
  }, isRunning ? 1000 : null);
  var start = useCallback(function () {
    var newPrevTime = new Date();
    setPrevTime(newPrevTime);
    setIsRunning(true);
    setSeconds(passedSeconds + Time.getSecondsFromPrevTime(newPrevTime, true));
  }, [passedSeconds]);
  var pause = useCallback(function () {
    setPassedSeconds(seconds);
    setIsRunning(false);
  }, [seconds]);
  var reset = useCallback(function () {
    var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
    var newAutoStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    var newPassedSeconds = Time.getSecondsFromExpiry(offset, true) || 0;
    var newPrevTime = new Date();
    setPrevTime(newPrevTime);
    setPassedSeconds(newPassedSeconds);
    setIsRunning(newAutoStart);
    setSeconds(newPassedSeconds + Time.getSecondsFromPrevTime(newPrevTime, true));
  }, []);
  return _extends({}, Time.getTimeFromSeconds(seconds), {
    start: start,
    pause: pause,
    reset: reset,
    isRunning: isRunning
  });
}