import { globalObject } from '@skbkontur/global-object';
import { stepper } from "../stepper";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
var noop = function noop() {

  /* do nothing */};
export var animation = function animation() {
  var animating = false;
  var currentPosition = 0;
  var currentVelocity = 0;
  var rafId = 0;
  var target = 0;
  var deltaHandler = noop;
  var animationEndHandler = noop;
  function reset() {
    currentVelocity = 0;
    currentPosition = 0;
    target = 0;
    animating = false;
    deltaHandler = noop;
    animationEndHandler = noop;
  }
  function inProgress() {
    return animating;
  }
  function cancel() {
    globalObject.cancelAnimationFrame == null || globalObject.cancelAnimationFrame(rafId);
    reset();
  }
  function finish() {
    animationEndHandler();
    cancel();
  }
  function animate(amount, onDelta, onEnd) {
    if (onEnd === void 0) {
      onEnd = noop;
    }
    target += amount;
    deltaHandler = onDelta;
    animationEndHandler = onEnd;
    var animateInternal = function animateInternal() {
      animating = true;
      var _stepper = stepper(currentPosition, currentVelocity, target),
        nextPosition = _stepper[0],
        nextVelocity = _stepper[1];
      var delta = nextPosition - currentPosition;
      deltaHandler(delta);
      if (nextPosition === target && nextVelocity === 0) {
        animationEndHandler();
        reset();
        return;
      }
      currentPosition = nextPosition;
      currentVelocity = nextVelocity;
      if (globalObject.requestAnimationFrame) {
        rafId = globalObject.requestAnimationFrame(animateInternal);
      }
    };
    if (!inProgress()) {
      animateInternal();
    }
  }
  return {
    animate: animate,
    inProgress: inProgress,
    cancel: cancel,
    finish: finish
  };
};