import { useMemo } from 'react';

import { Attachment, FileTypes } from 'src/types/attachments';

export function usePostAttachments(attachments: Attachment[]) {
  const mediaList = useMemo(
    () =>
      attachments.filter(
        attachment =>
          FileTypes.VIDEO === attachment.type ||
          FileTypes.IMAGE === attachment.type,
      ),
    // Use URLs to detect changes in a stable way
    [attachments.map(attachment => attachment.url).join(',')],
  );

  const fileList = useMemo(
    () => attachments.filter(attachment => attachment.type === FileTypes.FILE),
    [attachments.length],
  );

  const audioList = useMemo(
    () => attachments.filter(attachment => attachment.type === FileTypes.AUDIO),
    [attachments.map(attachment => attachment.url).join(',')],
  );

  const gif = attachments.find(attachment => attachment.type === FileTypes.GIF);

  return { mediaList, fileList, audioList, gif } as const;
}
