function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { useCallback, useRef } from 'react';
import useSetState from './use-set-state';
var MIN_DISTANCE = 10;

function getDirection(x, y) {
  if (x > y && x > MIN_DISTANCE) {
    return 'horizontal';
  }

  if (y > x && y > MIN_DISTANCE) {
    return 'vertical';
  }

  return '';
}

var INITIAL_STATE = {
  startX: 0,
  startY: 0,
  deltaX: 0,
  deltaY: 0,
  offsetX: 0,
  offsetY: 0,
  direction: ''
};

var useTouch = function useTouch(stateable) {
  var refState = useRef(INITIAL_STATE);
  var state = useSetState(INITIAL_STATE);
  var innerState = stateable ? state[0] : refState.current;

  var update = function update(value) {
    if (stateable) {
      state[1](value);
      return;
    }

    if (typeof value === 'function') {
      value = value(refState.current);
    }

    Object.entries(value).forEach(function (_ref) {
      var k = _ref[0],
          v = _ref[1];
      refState.current[k] = v;
    });
  };

  var isVertical = useCallback(function () {
    return innerState.direction === 'vertical';
  }, [innerState.direction]);
  var isHorizontal = useCallback(function () {
    return innerState.direction === 'horizontal';
  }, [innerState.direction]);

  var reset = function reset() {
    update({
      deltaX: 0,
      deltaY: 0,
      offsetX: 0,
      offsetY: 0,
      direction: ''
    });
  };

  var start = function start(event) {
    reset();
    update({
      startX: event.touches[0].clientX,
      startY: event.touches[0].clientY
    });
  };

  var move = function move(event) {
    var touch = event.touches[0];
    update(function (value) {
      // Fix: Safari back will set clientX to negative number
      var newState = _extends({}, value);

      newState.deltaX = touch.clientX < 0 ? 0 : touch.clientX - newState.startX;
      newState.deltaY = touch.clientY - newState.startY;
      newState.offsetX = Math.abs(newState.deltaX);
      newState.offsetY = Math.abs(newState.deltaY);

      if (!newState.direction) {
        newState.direction = getDirection(newState.offsetX, newState.offsetY);
      }

      return newState;
    });
  };

  return _extends({}, innerState, {
    move: move,
    start: start,
    reset: reset,
    isVertical: isVertical,
    isHorizontal: isHorizontal
  });
};

export default useTouch;