import { ExperimentStatus } from '@/enums';
import { NodeStatus } from '@/types';
import { parseJsonText } from '@/utils';
import { useEffect } from 'react';

export type MessageHandler = (
  experimentId: number,
  experimentInsId: number,
  status: string,
  finishTime: string,
  nodes: Record<string, NodeStatus>,
) => void;
export const useSSE = (
  experimentId: number,
  experimentInsId: number,
  status: ExperimentStatus,
  name: string,
  namespace: string,
  onMessage: MessageHandler,
) => {
  const isRunning = status === ExperimentStatus.Pending || status === ExperimentStatus.Running;
  useEffect(() => {
    if (isRunning) {
      const { origin } = location;
      const params = encodeURIComponent(`metadata.namespace=${namespace},metadata.name=${name}`);
      const evtSource = new EventSource(
        `${origin}/api/v1/realtimeStatus?listOptions.fieldSelector=${params}`,
        { withCredentials: false },
      );
      evtSource.onmessage = (event) => {
        const data = event?.data;
        if (!data) {
          return;
        }
        const dataJson = parseJsonText(data);
        const statusData = dataJson?.result?.object?.status;
        if (statusData) {
          const { finishedAt, phase, nodes } = statusData;
          onMessage(experimentId, experimentInsId, phase, finishedAt, nodes);
        }
      };

      evtSource.onerror = (error) => {
        console.error('SSE error: ', error);
      };

      return () => {
        evtSource.close();
      };
    }
  }, [experimentId, experimentInsId, isRunning, name, namespace, onMessage]);
};
