import { useMemo } from "react";
import { MachinePinged, PingMachine } from "types";
import { Key, mutationFetcher, NetworkError, useSWRMutation } from "units/swr";
import { blip } from "utils";
import { endpoints } from "utils/api";

type PingTriggerOptions = {
  onSuccess: (response: MachinePinged) => void;
  onError?: (error: Error) => void;
};
const usePingTrigger = (options: PingTriggerOptions) => {
  const { onSuccess } = options;
  const onError = useMemo(() => options.onError || ((error: Error) => blip.error(error.message)), [options.onError]);

  const { trigger: pingMachineTrigger } = useSWRMutation<MachinePinged, NetworkError, Key, PingMachine>(
    endpoints.network.machine.ping,
    mutationFetcher<PingMachine>,
    {
      onError,
      onSuccess,
      throwOnError: false
    }
  );
  return { pingMachineTrigger };
};
export default usePingTrigger;
