import { useEffect } from 'react';
import { useQueryClient } from 'react-query';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';

import { serviceManagementKeys } from '../queries';

const useTaskActivitiesUptader = (taskId: string) => {
  const socket = useSocket();
  const queryClient = useQueryClient();

  useEffect(() => {
    const handleNewActivity = () => {
      queryClient.invalidateQueries(
        serviceManagementKeys.activities.list(taskId),
      );
    };

    socket.listenEvent(
      EVENTS_SOCKETS.SERVICE_MANAGER_TASK_NEW_ACTIVITY,
      handleNewActivity,
    );

    return () => {
      socket.closeEvent(
        EVENTS_SOCKETS.SERVICE_MANAGER_TASK_NEW_ACTIVITY,
        handleNewActivity,
      );
    };
  }, [socket, queryClient]);
};

export default useTaskActivitiesUptader;
