import { useMemo } from 'react';

import { CallMode } from 'src/types/stream';

import {
  createGroupCallComparator,
  currentUserLastComparator,
  screenSharingComparator,
} from '../utils';

type UseSortParticipantsParams = {
  callMode: CallMode;
  hasScreenShare: boolean;
  isSpeakingOverThreshold: (sessionId: string) => boolean;
};

const useSortParticipants = ({
  callMode,
  hasScreenShare,
  isSpeakingOverThreshold,
}: UseSortParticipantsParams) => {
  const comparator = useMemo(() => {
    if (callMode === CallMode.SINGLE && !hasScreenShare) {
      return currentUserLastComparator;
    }

    if (callMode === CallMode.GROUP && !hasScreenShare) {
      return createGroupCallComparator(isSpeakingOverThreshold);
    }

    if (hasScreenShare) {
      return screenSharingComparator;
    }

    return undefined;
  }, [callMode, hasScreenShare, isSpeakingOverThreshold]);

  return comparator;
};

export default useSortParticipants;
