import { useCallback, useEffect } from 'react';

import { useCall } from '@stream-io/video-react-sdk';

import joinCall from 'src/assets/sound/join-call.mp3';
import leaveCall from 'src/assets/sound/leave-call.mp3';

const audioCache = new Map<string, () => Promise<void>>();

export const playSoundFromUrl = async (url: string) => {
  let doPlay = audioCache.get(url);

  if (!doPlay) {
    const canPlayPromise = new Promise<HTMLAudioElement>(resolve => {
      const audio = new Audio(url);
      audio.addEventListener('canplaythrough', () => resolve(audio), {
        once: true,
      });
    });

    doPlay = async () => {
      const audio = await canPlayPromise;
      audio.currentTime = 0;
      await audio.play();
    };

    audioCache.set(url, doPlay);
  }

  await doPlay();
};

const useConnectionSound = () => {
  const call = useCall();

  const isSelf = useCallback(
    (userId: string) => userId === call?.currentUserId,
    [call],
  );

  useEffect(() => {
    if (!call) return;

    const unlistenJoin = call.on('call.session_participant_joined', event => {
      if (isSelf(event.participant.user.id)) return;
      if (call.state.participantCount > 2) return;
      playSoundFromUrl(joinCall);
    });

    const unlistenLeave = call.on('call.session_participant_left', event => {
      if (!isSelf(event.participant.user.id)) return;
      playSoundFromUrl(leaveCall);
    });

    return () => {
      unlistenJoin();
      unlistenLeave();
    };
  }, [call, isSelf]);
};

export default useConnectionSound;
