export const PULL_REFRESH_THRESHOLD = 44;
export const PULL_REFRESH_MAX_DISTANCE = 52;
const PULL_RESISTANCE = 0.5;

export function beginPull({ direction, coordinate, atBoundary, refreshing }) {
  return {
    direction,
    start: coordinate,
    active: Boolean(atBoundary && !refreshing),
    distance: 0,
    armed: false
  };
}

export function movePull(state, coordinate) {
  if (!state?.active) return state;
  const delta = state.direction === "up" ? state.start - coordinate : coordinate - state.start;
  const distance = Math.min(PULL_REFRESH_MAX_DISTANCE, Math.max(0, delta * PULL_RESISTANCE));
  return { ...state, distance, armed: distance >= PULL_REFRESH_THRESHOLD };
}

export function finishPull(state) {
  return {
    state: state ? { ...state, active: false, distance: 0, armed: false } : state,
    shouldRefresh: Boolean(state?.active && state.armed)
  };
}
